Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python's FastAPI autogenerated OpenAPI/Swagger documentation page, how can I add more error http status codes?

Tags:

fastapi

FastAPI generates automatic swagger/openapi documentation.

In the tutorial at https://fastapi.tiangolo.com/tutorial/response-status-code there's an example

from fastapi import FastAPI
app = FastAPI()

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

If you run this, the .../docs page shows two http response options:

Status Code 201 for success and Status Code 422 for Validation error

The above tutorial shows a picture of this pageFastAPI docs)

I would like to document more responde status_code descriptions in the docs, for example code 403, "Forbidden"

While I can run exceptions like this in code

raise HTTPException(status_code=403, detail="Forbidden")

I have not found a way to describe them in the autogenerated docs.

Any idea how to do that?

like image 389
576i Avatar asked Jul 02 '20 21:07

576i


1 Answers

Does this solve your problem?

https://fastapi.tiangolo.com/advanced/additional-responses/

EDIT

With the response model you can add the different responses your API may return.

from pydantic import BaseModel
# Define your models here like
class model200(BaseModel):
    message: str = ""
    
@api.get("/my-route/", responses={200: {"response": model200}, 404: {"response": model404}, 500: {"response": model500}})
    async def api_route():
        return "I'm a wonderful route"

This will provide examples of your response models, making it simpler for users to interact with the api

like image 63
lsabi Avatar answered Nov 19 '22 00:11

lsabi