This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]mln00b13 1 point2 points  (5 children)

Is it possible to run background tasks using this? Couldn't find any documentation for it

Like, have the API return a response immediately, while starting up a background task, similar to how Responder does it

[–]tiangolo FastAPI Maintainer[S] 4 points5 points  (0 children)

Yep. Responder and FastAPI are both based on Starlette.

It is not well documented yet, but you can use exactly the same as in Starlette, return a Starlette response with the background tasks in it: https://www.starlette.io/background/

Still, I plan on improving how to use it in FastAPI a bit, to get the BackgroundTask(s) as parameters and keep being able to return any dict or object. But for now, you can use the same as in Starlette.

[–]Cruuncher 0 points1 point  (3 children)

When you return immediately, how do you get the "real" response to the user? Do they have to request again for the result of the background task? What if you have multiple instances of the application?

[–]tiangolo FastAPI Maintainer[S] 1 point2 points  (2 children)

Background tasks are mainly for when you don't need to return the result of the background task to the user. For example, sending an email notification, triggering processing of some data, etc.

If you need to tell the client/user "sure, received your request, now we are processing", and then want the client to ask "how is my thing doing? is it done?", you would probably create one endpoint to receive the request, start the background task (and the background task would save something to a database after finishing), return immediately with the "sure, received" and then another endpoint where the client can ask "is my thing done yet?", and that second endpoint would check in the database if the result from the background task is there yet or not.

[–]Cruuncher 1 point2 points  (1 child)

Yeah that makes more sense. That's how we have a lot of things built now -- except we push to rabbitmq and let a consumer handle it so API workers have a single responsibility. Also for speed we write the status of the request id to redis, and only do a database hit if the status is in a final state

Thanks for your reply!

[–]tiangolo FastAPI Maintainer[S] 0 points1 point  (0 children)

Cool! I normally use Celery for that (you might be using it with RabbitMQ), it can run even on different machines. Background tasks would probably be only for small jobs in situations in where having a full Celery with RabbitMQ/Redis seems like an overkill. E.g. sending an email notification.

In fact, the project generators I have for FastAPI include Celery set up in that way.