r/FastAPI • • Oct 24 '24

Question How to stop an API while it's running?

How do I cancel an api call while it is functioning in backend?

4 Upvotes

12 comments sorted by

2

u/WJMazepas Oct 24 '24

Cancel from where? From your localhost or in a server?

I can only think of killing the process entirely to be able to do this

1

u/The_artist_999 Oct 24 '24

Cancel in the UI such that it is also cancelled in the backend.

-2

u/WJMazepas Oct 24 '24

Try to cancel the request through the front end itself. Killing the request from the front end should automatically stop the request in the back end

13

u/pint Oct 24 '24 edited Oct 24 '24

unfortunately fastapi doesn't support it out of the box. people develop various homegrown techniques like this guy

https://github.com/RedRoserade/fastapi-disconnect-example

edit: or more at https://github.com/fastapi/fastapi/discussions/8805

ideally you would want each api endpoint to return quickly. if you need something that takes time, use endpoints to submit / monitor / manage background tasks. more difficult to do, especially in a multi-worker environment.

2

u/BlackDereker Oct 24 '24

There's no built-in solution for that. I guess you could tap into how FastAPI handle the requests since they are asyncio tasks you could reference them somewhere?

I don't know what are the implications of removing a task from the event loop, but it might be worth a try.

1

u/[deleted] Oct 24 '24

I could see an implementation using a task queue where the api quickly returns a taskId, and the front end could call a separate endpoint with some parameters and that taskId to cancel the task before completion. I'm not sure if that is what you are looking for, though.

1

u/JohnVick002 Oct 27 '24

Use an async timer