FASTAPI RESPONSE WITH status code ON CONDITION

Mahabubur Rahman
0

Certainly! In FastAPI, you can set the response status code based on certain conditions. Here's an example to illustrate this:

from fastapi import FastAPI, Response, status app = FastAPI() tasks = {"foo": "Listen to the Bar Fighters"} @app.put("/get-or-create-task/{task_id}", status_code=200) def get_or_create_task(task_id: str, response: Response): if task_id not in tasks: tasks[task_id] = "This didn't exist before" response.status_code = status.HTTP_201_CREATED return tasks[task_id]

In this example:

  • The endpoint /get-or-create-task/{task_id} is defined with a default status code of 200 (OK).
  • If the task_id does not exist in the tasks dictionary, a new task is created, and the status code is set to 201 (Created) using the response parameter.

This way, you can dynamically change the status code based on the condition within your path operation function.

Would you like more details or another example?


References

Post a Comment

0Comments
Post a Comment (0)