fastapi tutorial - advanced six (Response Status Code)

Reference content :

In the fastapi tutorial - advanced five (Response Model), we learned how to control the structure of the response body. In this section, we will learn how to use the http status code:

from fastapi import FastAPI

app = FastAPI()


@app.post("/items/", status_code=201)
async def create_item(name: str):
    return {
    
    "name": name}

Start the service, open it http://127.0.0.1:8000/docs, let's take a look at the response:
insert image description here

This example status_codedefines the status code by customizing, 201 represents a new resource, but what if we forget the corresponding number when using the status code? Here fastapi is very intimate, it provides us with enumeration values:
insert image description here

Also available here from starlette import status.

HTTP status code

  • Above 100 means "information". We rarely use them directly. Responses with these status codes cannot have a body.
  • 200 and above indicate a "success" response. These are the most commonly used.
    • The default status code is 200, which means everything is OK.
    • Another example is 201, "Created". Typically used after a new record has been created in the database.
    • The special case is 204, "No Content". This response is used when no content is returned to the client, so the response must have no body.
  • 300 and higher are used for "redirects". Responses with these status codes may or may not have a body, except for 304, "Not Modified", which MUST NOT have one.
  • 400 and higher are for "client error" responses. These are probably the second type used most often.
    • For a "Not Found" response, an example would be 404.
    • For general errors from clients, you can just use 400.
  • 500 and above are server errors. We almost never use them directly. When something goes wrong in your application code or in your server, it will automatically return one of these status codes.

The above chestnuts are all put on git, address: click here

Guess you like

Origin blog.csdn.net/weixin_40156487/article/details/108381824