question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] aiohttp integration best practice

See original GitHub issue

Description Hi. First of all great work with fastapi. I am currently evaluating shifting one of my api gateway from sanic / aiohttp to using fastapi / aiohttp. I have a bunch of microservices exposing various rest / grpc apis. The aim of the api gateway (with fast api) is to front all of them and provide a nice versioned, documented api contract. A typical api route can send requests to different endpoints and integrate results to formulate a nice response from the api gateway.

How can I […]?

  • My questions revolve around best way to use aiohttp client within routes driven through an apirouter?
  • Best way to initialize aiohttp ClientSession outside the routes as they provide a pool of tcp connections? There could be multiple clientSessions i.e. per type of microservice to provide consistency in timeouts dns behavior etc.
  • Sessions should be initialized before app start. I see support for events i.e. @app.on_event("startup"). Is it possible to add those for every apirouter rather than the main app. If so how can clientSession objects be available inside routes to do request?

Is it possible to […]? If all of this is not supported what would be the best approach to move forward.

Additional context Add any other context or screenshots about the feature request here.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:2
  • Comments:15 (6 by maintainers)

github_iconTop GitHub Comments

43reactions
wichertcommented, Oct 26, 2020

That is one way if you want create a new session for every request. You can also use a singleton approach:

class HttpClient:
    session: aiohttp.ClientSession = None

    def start(self):
        self.session = aiohttp.ClientSession()

    async def stop(self):
        await self.session.close()
        self.session = None

    def __call__(self) -> aiohttp.ClientSession:
        assert self.session is not None
        return self.session


http_client = HttpClient()

@app.on_event("startup")
async def startup():
    http_client.start()


@app.get("/fancy-path")
async def get_something(http_client: aiohttp.ClientSession = Depends(http_client)):
    r = await http_client.get("https://api.exampe.com")
    return r.json()
19reactions
raphaelauvcommented, Apr 21, 2020

Since I did not found any complete resource for that , I did a full example of :

fastAPI with an aiohttp client

full code and tests examples :

https://github.com/raphaelauv/fastAPI-aiohttp-example

Read more comments on GitHub >

github_iconTop Results From Across the Web

The aiohttp Request Lifecycle
Using a session as a best practice​​ However, if one uses aiohttp, one chooses asynchronous programming, a paradigm that makes the opposite trade-off:...
Read more >
Hands-on Intro to aiohttp - PyVideo
We'll provide best practises in building your aiohttp application, as well as how to write tests for your application.
Read more >
python asyncio/aiohttp sharing globals across project
What is the best practice to share such variables? I would like to create a globals.py module, which will define these variables. The...
Read more >
Integrating AIOHTTP Into a FastAPI App - YouTube
In this video I will show you how to make async requests in your FastAPI app using AIOHTTP. You'll see that it's easy...
Read more >
From Flask to aiohttp. By Manuel Miranda - Medium
... but this is totally against clean code practices, maintainability, DRY and some other best practices principles. So, the question is, how can...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found