Skip to main content

generate OpenAPI document and validate request & response with Python annotations.

Project description

Flask Pydantic Openapi

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.

Features

  • Less boilerplate code, only annotations, no need for YAML :sparkles:
  • Generate API document with Redoc UI or Swagger UI :yum:
  • Validate query, JSON data, response data with pydantic :wink:
  • Has support for request/response types other than JSON.

Quick Start

install with pip: pip install flask-pydantic-openapi

Examples

Check the examples folder.

Step by Step

  1. Define your data structure used in (query, json, headers, cookies, resp) with pydantic.BaseModel
  2. create flask_pydantic_openapi.Validator instance with the web framework name you are using, like api = Validator('flask')
  3. api.validate decorate the route with
    • query
    • body
    • headers
    • cookies
    • resp
    • tags
  4. access this data with context(query, body, headers, cookies) (of course, you can access these from the original place where the framework offered)
    • flask: request.context
  5. register to the web application api.register(app)
  6. check the document at URL location /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

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.

Demo

Try it with http post :8000/api/user name=alice age=18. (if you are using httpie)

Flask

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)

FAQ

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

flask_pydantic_openapi-0.4.2.tar.gz (17.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

flask_pydantic_openapi-0.4.2-py2-none-any.whl (21.7 kB view details)

Uploaded Python 2

File details

Details for the file flask_pydantic_openapi-0.4.2.tar.gz.

File metadata

  • Download URL: flask_pydantic_openapi-0.4.2.tar.gz
  • Upload date:
  • Size: 17.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.15.0 pkginfo/1.8.3 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.10.1 tqdm/4.64.1 CPython/2.7.18

File hashes

Hashes for flask_pydantic_openapi-0.4.2.tar.gz
Algorithm Hash digest
SHA256 1b8203e31a41bc344098fa88bf8ced1f7457933ca4c272640e5c97e923ee93d5
MD5 b9b3c8737c502cc8f25b2593ecaf7c92
BLAKE2b-256 0f120ac5cbb9b322bdb1078b66fefa1c2c56e9b3403d7bd99b5ba53f31680732

See more details on using hashes here.

File details

Details for the file flask_pydantic_openapi-0.4.2-py2-none-any.whl.

File metadata

  • Download URL: flask_pydantic_openapi-0.4.2-py2-none-any.whl
  • Upload date:
  • Size: 21.7 kB
  • Tags: Python 2
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.15.0 pkginfo/1.8.3 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.10.1 tqdm/4.64.1 CPython/2.7.18

File hashes

Hashes for flask_pydantic_openapi-0.4.2-py2-none-any.whl
Algorithm Hash digest
SHA256 0f6df8b6e789e09b9a0241ddf1371eeaedb2236864bf54f91ca802eed0b08b5e
MD5 8bd158b90ef2f9523e86e887aaae3d83
BLAKE2b-256 fec70cb7a3e6f456cf03d4093d2bf8674bbc1c49376158b408661f301ef34a3a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page