Embracing fastapi: three parameters and verification


Embracing fastapi: three parameters and verification

A few days ago, I wrote an advanced multi application management blueprint apirouter about fastapi. It may seem a little confused to some friends who have no foundation, so we will update them in the order from shallow to deep. Remember to pay attention to it

Let’s take a look at the outstanding features of fastapi, which are introduced on the official website as follows:

fast: very high performance, performance comparable toNodeJSandGo(thanks to starlette and pydantic).One of the fastest Python frameworks available
Fast coding: increase the speed of function development by about 200% to 300% *.
Fewer mistakes: reduces human errors by about 40% (developers).
visual: powerful editor support, less debugging time.
simple and easy: easy to use and learn, reduce the time of reading documents.
short: minimize duplicate code, multiple functions in each parameter declaration, and reduce coding errors.
robust: gets the code available for production. With automatic interactive API documentation.
Standards based: open standards based on (and fully compatible with) API:OpenAPI(formerly known as swagger) andJSON Schema

As mentioned earlier, one of the features of fastapi is based on the standard Python 3.6 type declaration and parameter verification function. All of this is attributed to pydant

Path parameters

Path parameters, namely URL path parameters, can be used to declare path “parameters” or “variables” with the same syntax as Python format strings, for example:

from fastapi import FastAPI
app = FastAPI()

async def read_item(item_id: int, q: str = None):
    return {"item": item_id, "q": q}

The value item of the path parameter_ ID will be passed as a parameter to the view function and run the command:

Uvicorn file name: app

The default port is 8000. You can also specify host and port, – host = — port = 8008

After running, open it in the browserhttp:// can see the response:


Where item_ ID is declared as int type, q is optional parameter, default is none, so Q in response is none

When we passhttp:// visiting 8000 / items / test, you can see a very friendly error response

    "detail": [
            "loc": [
            "msg": "value is not a valid integer",
            "type": "type_error.integer"

Because of the path parameter item_ The value of ID is “test” and cannot be converted to int, which is to participate in validation

Query parameters

The query parameters are also carried in the URL address, which is located in the URL at? The following set of key value pairs are separated by the & character, which is familiar to crawler friends, such as the following request parameters

Data = {"test": 1, "name": "Python Programming and practice"}
response = requests.get(url, params=data)

The query parameter passed by params is the query parameter response.url Print it out? Key value pair parameters after

So how does fastapi receive this parameter on the server? See the code

from fastapi import FastAPI

app = FastAPI()

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

async def read_item(skip: int = 0, limit: int = 10):
    return fake_items_db[skip : skip + limit]

Enter address after running:

The query parameters are:

  • Skip: the value is 0
  • Limit: the value is 10

Note that both parameters have default values, and you can choose to pass only one

Optional parameters

Similarly, you can declare the optional query parameter none by setting the default value of the optional query parameter to

from fastapi import FastAPI

app = FastAPI()

async def read_item(item_id: str, q: str = None):
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}

Required query parameters

Remove none from Q: STR in the above code, and Q becomes a must query parameter, that is, must be passed. Otherwise, an error will be prompted

    "detail": [
            "loc": [
            "msg": "field required",
            "type": "value_error.missing"

To sum up, the required parameters, default parameters and optional parameters may be used in the actual code, as follows:

from fastapi import FastAPI

app = FastAPI()

async def read_user_item(item_id: str, needy: str, skip: int = 0, limit: int = None):
    item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
    return item

In this case, there are three query parameters:

  • Need is a required str.
  • Skip, int, the default value is 0.
  • Limit, optional int.

There is also a path parameter: item_ ID, STR type

Request body parameters

To send the request body, you must use one: post, put, delete or patch. You need to import the base model of Python

from fastapi import FastAPI
import uvicorn
from pydantic import BaseModel

app = FastAPI()

class CommonItem(BaseModel):
    token: str
    message_id: str
    to_id: str
    from_info: str
    Strategy: int or STR = 0 ා the default value is 0. You can not pass this parameter, but you cannot pass an empty string
    Type: STR or int ා both STR and int types are supported
    from_id: str
    to_info: str
    content: str = None

async def tests(item: CommonItem):
    return item

As you can see, a commonitem model is created. With the declared model, the following functions can be implemented:

  • Read the body of the request as JSON
  • Automatically converts parameters based on the type of declaration
  • Validate the data, and if the data is invalid, it returns a clear error indicating the exact location and source of the error data
  • Receive the received data item in the parameter, and get all properties and all editor support

Embracing fastapi: three parameters and verification

At the same time, fastapi can automatically help us identify the request body parameters, path parameters and query parameters, and accurately obtain the parameter data. For example, the following code:

from fastapi import FastAPI
from pydantic import BaseModel

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

app = FastAPI()

async def create_item(item_id: int, item: Item, q: str = None):
    result = {"item_id": item_id, **item.dict()}
    if q:
        result.update({"q": q})
    return result

The above codes and parameters will be automatically identified:

  • item_ ID,: path parameter
  • q: A single type of a parameter (such as int, float, STR, bool, etc.) will be interpreted as a query parameter
  • Item: if the parameter is declared to be of the type of the python model, it will be interpreted as a request body

Embracing fastapi: three parameters and verification

Recommended Today

Let me also summarize the knowledge of nginx

Recently, I want to deeply study the related knowledge of nginx, so I summarize the following contents. Nginx configuration parameters Nginx common commands Nginx variable Virtual host configuration Nginx’s own module Fastcgi related configuration Common functions Load balancing configuration Static and dynamic separation configuration Anti theft chain What is nginx? Nginx is a free, open […]