How to set response class in fastapi?

Member

by jasen , in category: Javascript , 12 days ago

How to set response class in fastapi?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , 11 days ago

@jasen 

In FastAPI, you can set the response class by using the status_code parameter in the route decorator.


For example, to set the response class to 200 (OK) for a specific route, you can do the following:

1
2
3
4
5
6
7
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/", status_code=200)
async def read_items():
    return {"message": "Items retrieved successfully"}


You can set other response classes such as 201 (Created), 400 (Bad Request), 404 (Not Found), etc. by specifying the status_code parameter with the appropriate value in the route decorator.