[PYTHON] How to use FastAPI ③ OpenAPI

What is written

--Memo when using FastAPI (It may be wrong because it is a personal memo ...) --Excerpts related to OpenAPI behavior from the official website documentation

reference

FastAPI

environment

Build a Docker environment and check the operation

Docker FastAPI

Start-up

bash


# main.If py is in the root directory
$ uvicorn main:app --reload --host 0.0.0.0 --port 8000

# main.If py is not in the root directory
$ uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

Source

main.py


import uvicorn
from fastapi import FastAPI, Query, Path, Body
from typing import Optional
from pydantic import BaseModel, Field

#Description of each tag
tags_metadata = [
    {
        "name": "users",
        "description": "Operations with users. The **login** logic is also here.",
    },
    {
        "name": "items",
        "description": "Manage items. So _fancy_ they have their own docs.",
        "externalDocs": {
            "description": "Items external docs",
            "url": "https://fastapi.tiangolo.com/",
        },
    },
]

items = {
    1: {"item_no": 1, "item_name": "name1", "price": 100},
    2: {"item_no": 2, "item_name": "name2", "price": 200},
    3: {"item_no": 3, "item_name": "name3", "price": 300},
}

users = {
    1: {"user_no": 1, "user_name": "name1", "email": "[email protected]"},
    2: {"user_no": 2, "user_name": "name2", "email": "[email protected]"},
    3: {"user_no": 3, "user_name": "name3", "email": "[email protected]"},
}

#Schema description, data example
class Item(BaseModel):
    name: str
    description: Optional[str] = Field(
        None,
        title="The description of the item",
        max_length=300
    )
    price: float = Field(
        ...,
        gt=0,
        description="The price must be greater than zero"
    )
    tax: Optional[float] = None

    class Config:
        schema_extra = {
            "example": {
                "name": "example_name",
                "description": "example_description",
                "price": 100,
                "tax": 10,
            }
        }

#OpenAPI itself settings
app = FastAPI(
    title="FastAPI Sample Project",
    description="This is a very fancy project, with auto docs for the API and everything",
    version="1.0.1",
    openapi_tags=tags_metadata,
    docs_url="/api/v1/docs",
    redoc_url="/api/v1/redoc",
    openapi_url="/api/v1/openapi.json",
)

#Setting of each url
@app.get(
    "/items",
    tags=["items"],
    summary="read items summary",
)
async def read_items(
    option: Optional[str] = Query(
        None,
        title="Query Parameter Title",
        description="Query Parameter Description",
    ),
):
    return {"items": items}

@app.get(
    "/items/{item_no}",
    tags=["items"],
    summary="read item summary",
)
async def read_item(
    item_no: str = Path(
        None,
        title="Path Parameter Title",
        description="Path Parameter Description",
        deprecated=True,
    ),
):
    return {"item": items[item_no]}

@app.post(
    "/items/{item_no}",
    tags=["items"],
    summary="create item summary",
)
async def create_item(
    item_id: int,
    item: Item = Body(..., embed=True),
):
    results = {"item_id": item_id, "item": item}
    return results

@app.get(
    "/users",
    tags=["users"],
)
async def read_users():
    """
    Create an item with all the information:

    - **name**: each item must have a name
    - **description**: a long description
    - **price**: required
    - **tax**: if the item doesn't have tax, you can omit this
    - **tags**: a set of unique tag strings for this item
    -FastAPI document reflection test
    """
    return {"users": users}

@app.get(
    "/user/{user_no}",
    tags=["users"],
)
async def read_user(user_no: str):
    return {"user": users[user_no]}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Generated document

OpenAPI.png

Recommended Posts

How to use FastAPI ③ OpenAPI
How to use FastAPI ① Tutorial --User Guide
How to use xml.etree.ElementTree
How to use Python-shell
How to use tf.data
How to use virtualenv
How to use Seaboan
How to use image-match
How to use shogun
How to use Pandas 2
How to use FastAPI ② Advanced --User Guide
How to use numpy.vectorize
How to use pytest_report_header
How to use partial
How to use Bio.Phylo
How to use SymPy
How to use x-means
How to use WikiExtractor.py
How to use IPython
How to use virtualenv
How to use Matplotlib
How to use iptables
How to use numpy
How to use TokyoTechFes2015
How to use venv
How to use dictionary {}
How to use Pyenv
How to use list []
How to use python-kabusapi
How to use OptParse
How to use return
How to use dotenv
How to use pyenv-virtualenv
How to use Go.mod
How to use imutils
How to use import
How to use Qt Designer
How to use search sorted
[gensim] How to use Doc2Vec
python3: How to use bottle (2)
How to use the generator
[Python] How to use list 1
How to use Python argparse
How to use IPython Notebook
How to use Pandas Rolling
[Note] How to use virtualenv
How to use redis-py Dictionaries
Python: How to use pydub
[Python] How to use checkio
[Go] How to use "... (3 periods)"
How to use Django's GeoIp2
[Python] How to use input ()
How to use the decorator
[Introduction] How to use open3d
How to use Python lambda
How to use Jupyter Notebook
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Google Colaboratory
How to use Python bytes