Security News
Introducing the Socket Python SDK
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
flask-pydantic-openapi
Advanced tools
generate OpenAPI document and validate request & response with Python annotations.
A library to make it easy to add OpenAPI documentation to your Flask app, and validate the requests using Pydantic.
This library began as a fork of Flask-Pydantic-Spec, but as we made changes we thought other people might be interested in our approach.
install with pip: pip install flask-pydantic-openapi
Check the examples folder.
pydantic.BaseModel
flask_pydantic_openapi.Validator
instance with the web framework name you are using, like api = Validator('flask')
api.validate
decorate the route with
query
body
headers
cookies
resp
tags
context(query, body, headers, cookies)
(of course, you can access these from the original place where the framework offered)
request.context
api.register(app)
/apidoc/redoc
or /apidoc/swagger
If the request doesn't pass the validation, it will return a 422 with JSON error message(ctx, loc, msg, type).
How to add summary and description to endpoints?
Just add docs to the endpoint function. The 1st line is the summary, and the rest is the description for this endpoint.
How to add description to parameters?
Check the pydantic docs about description in Field
.
Any config I can change?
Of course. Check the config document.
You can update the config when you init the validator like:
from flask_pydantic_openapi import FlaskPydanticOpenapi
FlaskPydanticOpenapi("flask", title="Demo API", version="v1.0", path="doc")
What is a
Response
and how to use it?
To build a response for the endpoint, you need to declare the status code with format HTTP_{code}
and corresponding data (optional).
from flask_pydantic_openapi import Response
Response(HTTP_200=None, HTTP_403=ForbidModel)
Response('HTTP_200') # equals to Response(HTTP_200=None)
What should I return when I'm using the library?
No need to change anything. Just return what the framework required.
How to logging when the validation failed?
Validation errors are logged with INFO level. Details are passed into extra
.
How can I change the response when there is a validation error? Can I record some metrics?
This library provides before
and after
hooks to do these. Check the doc or the test case. You can change the handlers for Flask-Pydantic-Spec or for a specific endpoint validation.
Try it with http post :8000/api/user name=alice age=18
. (if you are using httpie
)
from flask import Flask, request, jsonify
from pydantic import BaseModel, Field, constr
from flask_pydantic_openapi import FlaskPydanticOpenapi, Response, Request
class Profile(BaseModel):
name: constr(min_length=2, max_length=40) # Constrained Str
age: int = Field(
...,
gt=0,
lt=150,
description='user age(Human)'
)
class Config:
schema_extra = {
# provide an example
'example': {
'name': 'very_important_user',
'age': 42,
}
}
class Message(BaseModel):
text: str
app = Flask(__name__)
api = FlaskPydanticOpenapi('flask')
@app.route('/api/user', methods=['POST'])
@api.validate(body=Request(Profile), resp=Response(HTTP_200=Message, HTTP_403=None), tags=['api'])
def user_profile():
"""
verify user profile (summary of this endpoint)
user's name, user's age, ... (long description)
"""
print(request.context.json) # or `request.json`
return jsonify(text='it works')
if __name__ == "__main__":
api.register(app) # if you don't register in api init step
app.run(port=8000)
ValidationError: missing field for headers
The HTTP headers' keys in Flask are capitalized.
You can use pydantic.root_validators(pre=True)
to change all the keys into lower cases or upper cases.
ValidationError: value is not a valid list for query
Since there is no standard for HTTP query with multiple values, it's hard to find the way to handle this for different web frameworks. So I suggest not to use list type in query until I find a suitable way to fix it.
FAQs
generate OpenAPI document and validate request & response with Python annotations.
We found that flask-pydantic-openapi demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
Security News
Floating dependency ranges in npm can introduce instability and security risks into your project by allowing unverified or incompatible versions to be installed automatically, leading to unpredictable behavior and potential conflicts.
Security News
A new Rust RFC proposes "Trusted Publishing" for Crates.io, introducing short-lived access tokens via OIDC to improve security and reduce risks associated with long-lived API tokens.