Just a quick ramble
We talked a little bit about cookies and headers, but today we’re going to talk a little bit about responses
The response is the return value of the interface, the status code, etc., which is required. The data returned is mainly used as a reference for the front-end debug page and testing.
Response model
Fastapi simply uses the response_model parameter in any path (@app.get(), @app.post(), @app.put(), @app.delete()) operation to declare the model used for the response.
Note: response_model is an argument to the “decorator” method (get, POST, etc.). Unlike all the previous arguments and request bodies, it is not part of the path manipulation function.
from typing import List, Optional
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
app = FastAPI()
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
tagg: List[str] = []
@app.post("/items/", response_model=Item)
async def create_item(item: Item):
return item
Copy the code
Response_model is defined as the return value, because the response_model is assigned by Item and returns the same data as the input
Start the service:
PS E:\git_code\python-code\fastapiProject> uvicorn response_main:app --reload
Copy the code
Request interface:
POST http://127.0.0.1:8000/items
Request parameters:
{"name": "zhang ", "price": 3.2}Copy the code
Request result:
{" name ":" zhang ", "description", null, "price" : 3.2, "tax", null, "tagg" : []}Copy the code
If we enter a password, then the above return the same data as the input is not suitable for this requirement, so we have to define the output model:
from typing import List, Optional
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
from fastapi import status
app = FastAPI()
class UserIn(BaseModel):
username: str
password: str
email: EmailStr
full_name: Optional[str] = None
class UserOut(BaseModel):
username: str
email: EmailStr
full_name: Optional[str] = None
@app.post("/user/", response_model=UserOut)
async def create_user(user: UserIn):
return user
Copy the code
Note information:
EmailStr is the mail type. UserIn is the input model and UserOut is the output model. Response_model =UserOut is the received output model. User: UserIn is the received input model. Return user Although the input model is returned, we have already declared the output model, so FastAPI will take care of filtering out all data that is not declared in the output model.
Start the service:
PS E:\git_code\python-code\fastapiProject> uvicorn response_main:app --reload
Copy the code
Request interface:
POST http://127.0.0.1:8000/user
Request parameters:
{
"username": "lifeng",
"password":"123456",
"email": "[email protected]",
"full_name": "debuglifeng"
}
Copy the code
Request result:
{
"username": "lifeng",
"email": "[email protected]",
"full_name": "debuglifeng"
}
Copy the code
The response_model_exclude_unset parameter returns only the specified value and defines an ID to handle the specified return value.
Response_model_exclude_unset preach True
from typing import List, Optional
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
from fastapi import status
app = FastAPI()
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
tagg: List[str] = []
@app.post("/items/", response_model=Item, response_model_exclude_unset=True)
async def create_item(item: Item):
return item
Copy the code
Response_model_exclude_unset =True; response_model_exclude_unset=True;
Start the service:
PS E:\git_code\python-code\fastapiProject> uvicorn response_main:app --reload
Copy the code
Request interface:
POST http://127.0.0.1:8000/items
Request parameters:
{"name": "zhang ", "price": 3.2}Copy the code
Request result:
{"name": "zhang ", "price": 3.2}Copy the code
Specify the return value
Send the specified ID to the path operation. Such data is available in the database:
from typing import List, Optional from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Default(BaseModel): name: STR description: STR = None Price: float Tax: float = 10.5 Tags: List[STR] = [] items = {" foo": {"name": "Foo", "price", 50.2}, "bar" : {" name ":" bar ", "description" : "The bartenders", "price" : 62, "tax", 20.2}, "baz" : {" name ":" Baz ", "description" : None, "price" : 50.2, "tax" : 10.5, "tags" : [] }, } @app.post( "/default/{item_id}", response_model=Default) async def default_items(item_id: str): return items[item_id]Copy the code
Items is a large dictionary that can then fetch data from the database
Start the service:
PS E:\git_code\python-code\fastapiProject> uvicorn response_main:app --reload
Copy the code
Request interface:
POST http://127.0.0.1:8000/default/bar
Request parameters:
{"name": "zhangsan", "price": 10.22}Copy the code
Request result:
{" name ":" Bar ", "description" : "The bartenders", "price" : 62.0, "tax" : 20.2, "tags" : []}Copy the code
Response_model_include and response_model_exclude, response_model_include, response_model_exclude, response_model_exclude, response_model_include, response_model_exclude, response_model_exclude:
response_model_include
The ginseng
from typing import List, Optional from fastapi import FastAPI from pydantic import BaseModel, EmailStr app = FastAPI() class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional [float] = 3.33 tagg: List[str] = [] @app.post("/items/", response_model=Item, response_model_include={"name"}) async def create_item(item: Item): return itemCopy the code
Request parameters:
{"name": "zhang ", "price": 3.2}Copy the code
Request result:
{"name": "zhang SAN"}Copy the code
response_model_exclude
The ginseng
from typing import List, Optional from fastapi import FastAPI from pydantic import BaseModel, EmailStr app = FastAPI() class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional [float] = 3.33 tagg: List[str] = [] @app.post("/items/", response_model=Item, response_model_exclude={"price"}) async def create_item(item: Item): return itemCopy the code
Request parameters:
{"name": "zhang ", "price": 3.2}Copy the code
Request result:
{" name ":" zhang ", "description", null, "tax" : 3.33, "tagg" : []}Copy the code
Response status code
Fastapi only needs to use the status_code parameter in any path (@app.get(), @app.post(), @app.put(), @app.delete()) operation to declare the HTTP status code for the response.
Pass the status code directly
from fastapi import FastAPI
app = FastAPI()
@app.post("/items/", status_code=201)
async def items(name: str):
return {"name": name}
Copy the code
The status_code parameter receives a number representing the HTTP status code.
The status status package is imported
from fastapi import FastAPI, status
app = FastAPI()
@app.post("/items/", status_code=status.HTTP_201_CREATED)
async def items(name: str):
return {"name": name}
Copy the code
HTTP status code description:
- Status codes 100 and above are used for message responses. You rarely use them directly. A response with these status codes cannot have a response body.
- Status codes 200 and above are used for successful responses. These are the ones you use most often.
- 200 is the default status code, which means everything is “normal.”
- Another example would be 201, “Created.” It is typically used after a new record has been created in the database.
- A special example is 204, “no content.” This response is used when no content is returned to the client, so the response cannot contain the response body.
- Status codes 300 or higher are used for redirection. Responses with these status codes may or may not have a response body, with the exception of 304 “Unmodified”, which may not contain a response body.
- Status codes 400 and above are used for client error responses. These are probably your second most commonly used types.
- An example is 404 for a “not found” response.
- For common errors from clients, you can just use 400.
- Status codes 500 and above are used for server-side errors. You almost never use them directly. When something goes wrong in your application code or in some part of the server, it automatically returns one of these status codes.
Today, let’s stop here. The above summary may help you, or may not help you, but I still hope to help you. If there is doubt, ambiguity, direct private message will be timely revised and released; I am looking forward to your three-touch [like, favorites, share] oh, thank you!
Unfinished, to be continued…
Have been trying, I hope you are too!
Wechat search public account: use Python