“This is my 28th day of participating in the First Challenge 2022. For details: First Challenge 2022.”

preface

  • One of the methods of interface parameter passing is to pass the Request data by sending a Request Body
  • In FastAPI, the Pydantic model is advocated to define the request body
  • This article will go into details about sending request bodies without Using Pydantic and using Pydantic

Pay attention to

  • Request bodies are not unique to POST requests, but POST is more common
  • The request body can be used in PUT, DELETE, and PATCH requests
  • You can use the body of a GET request, but only in very extreme cases, and the Swagger API does not display the body of a GET request

Chestnuts without Pydantic

from fastapi import FastAPI import uvicorn app = FastAPI() @app.post("/items") async def read_item(item: dict): return {"item": item} if __name__ == "__main__": Run (app="6_request:app", host="127.0.0.1", port=8080, reload=True, debug=True) uvicorn.run(app="6_request:app", host="127.0.0.1", port=8080, reload=True, debug=True)Copy the code

Specify the type of the query parameter as dict

The result of the request for correct parameter transmission

View the request header

It is in JSON format, as expected

Focus on

  • Make sure to use JSON to make postman requests
  • Because you are receiving dict, FastAPI automatically converts JSON strings to dict
  • In this scenario, although the query parameter is called item, the field name and the number of fields in the request body can be arbitrary

Result of the request for incorrect parameter passing

After text is selected, FastAPI cannot parse the request body as dict because it is not a JSON string

View the request header

 

Type is text

Chestnut with Dict instead of Dict

Dict is a class provided by the Typing module that specifies the data types of key-value pairs

From typing import Dict from fastAPI import fastapi app = fastapi () @app.post("/Dict/") Float async def create_index_weights(weights: Dict[STR, float]): return weightsCopy the code

The benefits of using Dict versus straight Dict

Declared as Dict[STR, float], FastAPI validates each key-value pair with a friendly error message if it fails

The result of the request for correct parameter transmission

Verify the result of a failed request

Friendly error

Using the Pydantic model (recommended)

The actual chestnuts

From FastAPI import FastAPI from typing Import Optional from Pydantic Import BaseModel app = fastAPI () # customize a Pydantic BaseModel: name: STR description: Optional[STR] = None price: float tax: Optional[float] = None @app.post("/items/") # item async def create_item(item: item): return itemCopy the code

FastAPI does these things after specifying the Pydantic model as an argument

  1. Identify the request body as a JSON string
  2. Convert the field value to the corresponding type (if necessary)
  3. Validate data, and if validation fails, a clear error is returned, specifying the location and information of the faulty data
  4. The item receives the complete request body data, has all the attributes and their types, and the IDE gives corresponding intelligent hints
  5. JSON schemas are automatically generated for Pydantic models, which become part of the OpenAPI Schema generation and are displayed in the interface documentation

The result of the request for correct parameter transmission

Normal parameter transmission, all attributes according to the specified type of data transmission

Automatic conversion of field value types

  • Name: STR passes data of type bool
  • Description: STR passes data of type float
  • Price: float passes data of type int
  • Tax: float Passes data of type bool

FastAPi automatically converts the value passed in to a value of the specified type

  • Convert true to STR, which is “true”
  • Convert 12.22 to STR, that is, “12.22”
  • Convert 12 to float, 12.0
  • Convert true to float, that is, 1.0

If the conversion fails, type_ERROR is reported (as shown below)

Verify the result of a request for failed data

Check out the Swagger API documentation

Schema part

The JSON Schema for the Model becomes part of the Swagger APi documentation

Sample value section

IDE Smart Tips

Knowing that the name attribute is of type STR, the IDE intelligently prompts for methods built into STR

Request Body + Path + Query Parameters synthesis chestnut

  • You can declare request body, path parameters, and query parameters at the same time
  • FastAPI can identify each of them and get the data from the right place

The actual code

from typing import Optional 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(# path parameter item_id: Item: item, # query parameter name: Optional[STR] = None): result = {"item_id": Item_id, **item.dict()} print(result) if name: # result.update({"name": name}) return resultCopy the code

FastAPI identifies the logic of the parameters

  • If the parameter is also declared in the path, it will be interpreted as the path parameter [item_id].
  • If the argument is a singular type (such as int, float, STR, boo L, etc.), it will be interpreted as a query parameter [name]
  • If a parameter is declared as a Pydantic model type, it is resolved to the request body [item].

The result of the request for correct parameter transmission

Pycharm Console Output results

Prints the value of result

{" item_id ": 1234, 'name' : 'small pineapple', 'description' : 'description, not mandatory,' price: 12.22, 'tax: 0.0}Copy the code

Check out the Swagger API documentation