snok / asgi-correlation-id

Request ID propagation for ASGI apps
MIT License
370 stars 29 forks source link

How to get Correlation ID inside the view function in FastAPI? #11

Closed raghavsikaria closed 2 years ago

raghavsikaria commented 2 years ago

Hey author, thanks for the amazing work! Our team is planning to onboard this library in our projects. I have been trying to retrieve the created correlation ID inside a view function in FastAPI but I am not able to query it somehow. I have tried querying the request.headers and request.body(), and am still not able to find it. How can I get that?

sondrelg commented 2 years ago

Hi @raghavsikaria! You should be able to get the correlation ID value by doing this:

from asgi_correlation_id.context import correlation_id as correlation_id_context_var

correlation_id = correlation_id_context_var.get()

Just put the last line inside your view function 👍

raghavsikaria commented 2 years ago

Oh, great thanks! So let's say I have a couple of thousand concurrent requests hitting that particular endpoint. Will I get the correct correlation ID for each of their contexts this way?

sondrelg commented 2 years ago

Yes you will!

That's why we decided to use context vars to store this type of state - each request should get its own ID, and the ID should be accessible anywhere in your application code 👍 That's the intention at least, but feel free to test it out and report back 🙂

raghavsikaria commented 2 years ago

Cool, thanks for the prompt help!

sondrelg commented 2 years ago

No worries, happy to see others using the package 👏

Feel free to star the repo if you find it helpful, as it will help raise our visibility a little 🙂

raghavsikaria commented 2 years ago

Done, sure. My Bad!