FastAPI requests to internal endpoint #6946
-
|
I was working on a project recently and was experiencing problems with FastAPI interacting with the requests library. The goal I’m trying to achieve is to have a health_status endpoint function hit the health version endpoint as well. I have recreated the problem with 2 smaller projects, a simple fastapi and a simple flask. Flask is able to achieve the goal, but Fastapi freezes up when trying to do it. Here is the code using flask. When hitting the “/health/status” endpoin it should return {“message”: “Hello World”} however it freezes up the entire api. It doesn’t even allow me to hit the root endpoint afterwards unless I rerun the program. However, I am able to hit the root endpoint if I hit it before calling “/health/status." CodeSimilarly, the code using flask is listed below. This works just fine, where if I hit “/health/status” then it will return “Hello World” DescriptionAs mentioned above, instead of returning "Hello World" like it should, it just ties up the whole api when using FastAPI. Environment
|
Beta Was this translation helpful? Give feedback.
Replies: 6 comments
-
You are executing a synchronous function inside a coroutine, of course, it is going to block. But it shouldn't take longer than >100ms. |
Beta Was this translation helpful? Give feedback.
-
|
Use |
Beta Was this translation helpful? Give feedback.
-
|
You can use normal function to solve now. @app.get("/health/status")
def health():
resp = requests.get(url="http://127.0.0.1:8000/")
return resp.text |
Beta Was this translation helpful? Give feedback.
-
|
The thing is that you're calling a blocking synchronous function on a
Approach 2 performs better. |
Beta Was this translation helpful? Give feedback.
-
|
@Kludex Can I get to know more details the reason? why the server gets freezing infinitely as requesting "/health/status" in original code from @jayycarter. I'm wondering why "requests.get()" blocks "async def health()" INFINITELY, not just block some time. |
Beta Was this translation helpful? Give feedback.
-
|
I think the reason infinite freezing is because "async def health()" is coroutine. |
Beta Was this translation helpful? Give feedback.
The thing is that you're calling a blocking synchronous function on a
coroutineand it will block the event loop. Possible solutions are:health()synchronous i.e. remove theasync. This way it will run in another thread.root()in this case).Approach 2 performs better.