You can declare a parameter of type Response in your path operation function (as you can do for cookies and headers).
And then you can set the status_code in that temporal response object.
fromfastapiimportFastAPI,Response,statusapp=FastAPI()tasks={"foo":"Listen to the Bar Fighters"}@app.put("/get-or-create-task/{task_id}",status_code=200)defget_or_create_task(task_id:str,response:Response):iftask_idnotintasks:tasks[task_id]="This didn't exist before"response.status_code=status.HTTP_201_CREATEDreturntasks[task_id]
And then you can return any object you need, as you normally would (a dict, a database model, etc).
And if you declared a response_model, it will still be used to filter and convert the object you returned.
FastAPI will use that temporal response to extract the status code (also cookies and headers), and will put them in the final response that contains the value you returned, filtered by any response_model.
You can also declare the Response parameter in dependencies, and set the status code in them. But keep in mind that the last one to be set will win.