fastapi User Guide (path parameters, query parameters, request body)

Posted by dross613 on Thu, 30 Sep 2021 21:05:11 +0200


learn from https://fastapi.tiangolo.com/zh/tutorial/

1. Step 1

  • pip install fastapi[all]
from fastapi import FastAPI
my_app = FastAPI() # my_app instance, whose name corresponds to that in the terminal
@my_app.get("/")
async def root():
    return {"message" : "Hello World"}

  • http operation:
    POST: create data.
    GET: read data.
    PUT: update data.
    DELETE: DELETE data.

@my_app.get("/") tells FastAPI that the function below it is responsible for processing the following access requests:

  • Request path is/
  • Use get operation

The function can return a dict, list, a single value like str, int, and so on. You can also return the Pydantic model

1.1 summary

  • Import FastAPI
  • Create an app instance
  • Write a path operation decorator (such as @ app.get("/"))
  • Write a path operation function (such as def root():...) above
  • Run the development server (such as uvicon Main: app -- reload)

2. Path parameters

  • The function parameter is consistent with the name in {}
@my_app.get("/items/{item_id}")
async def read_item(item_id):  # Be consistent with {} above
    return {"itemid": item_id} # Return string
  • Parameter type limit: type. If the parameter types do not match, an error will be reported
@my_app.get("/items/{item_id}")
async def read_item(item_id: int):  # Be consistent with {} above
    return {"itemid": item_id} # Return int
  • file http://127.0.0.1:8000/docs , http://127.0.0.1:8000/redoc

2.1 order is important

@my_app.get("/users/me")
async def read_user_me():
    return {"user_id": "the current user"}


@my_app.get("/users/{user_id}")
async def read_user(user_id: str):
    return {"user_id": user_id}


If the above two functions are in reverse order, the results are as follows

2.2 preset values

  • Using Enum
from enum import Enum

app = FastAPI()


class ModelName(str, Enum): # Inherits from string enumeration. It must be a string and the specified enumeration value
    alexnet = "alexnet"
    resnet = "resnet"
    lenet = "lenet"


@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
    if model_name == ModelName.alexnet:
        return {"model_name": model_name, "message": "Deep Learning FTW!"}
    if model_name.value == "lenet":
        return {"model_name": model_name, "message": "LeCNN all the images"}
    return {"model_name": model_name, "message": "Have some residuals"}

You can use model_name.value or usually your_enum_member.value to get the actual value


2.3 path parameters including paths

  • Parameter name in parameter {}: Path: there is no space before and after, without: path. The path parameter with / cannot be recognized
@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
    return {"file_path": file_path}

3. Query parameters

fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]


@app.get("/items")
async def read_item(skip: int = 0, limit: int = 10):
    return fake_items_db[skip:skip + limit]
  • use? Start with & split between parameters
from typing import Optional
@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Optional[str] = None):
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}

3.1 query parameter type conversion

from typing import Optional


@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Optional[str] = None, short: bool = False):
    item = {"item_id" : item_id}
    if q:
        item.update({"q" : q})
    if not short:
        item.update(
            {"description": "This is an amazing item that has a long description"}
        )
    return item

Enter short =, followed by 1, True, true, yes, on, On, YES. Any deformable body has the same effect and is true

  • The order of multiple parameters is not affected. It can be found by name
@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(
        item_id: str, user_id: int, q: Optional[str] = None, short: bool = False
):
    item = {"item_id": item_id, "owner_id": user_id}
    if q:
        item.update({"q": q})
    if not short:
        item.update(
            {"description": "This is an amazing item that has a long description"}
        )
    return item
  • item_id: str, user_id: int, change the position of two variables. It doesn't matter

4. Requestor

The request body is the data sent by the client to the API
The response body is the data sent by the API to the client

Use the Pydantic model to declare the request body

from typing import Optional

from Pinyin2Hanzi import Item
from fastapi import FastAPI
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: Optional[str]=None
    price:float
    tax:Optional[float] = None

app = FastAPI()

@app.put("/items/{item_id}")
async def create_item(item_id: int, item: Item, q: Optional[str] = None):
    result = {"item_id": item_id, **item.dict()}
    if q:
        result.update({"q": q})
    return result

  • You can also declare the request body, path parameters, and query parameters at the same time.
    Function parameters will be identified according to the following rules:
    1. If the parameter is also declared in the path, it will be used as the path parameter
    2. If the parameter belongs to a single type (such as int, float, str, bool, etc.), it will be interpreted as a query parameter
    3. If the type of the parameter is declared as a Pydantic model, it will be interpreted as the request body

Topics: Python FastAPI