Skip to content

Add a base_url option to ClientSession like httpx does #6013

Closed
@dcordb

Description

Is your feature request related to a problem?

Yes, I would like to have the option to declare a base_url to a ClientSession, such that every request use the same base_url for that session.

Instead of writing:

async with aiohttp.ClientSession() as session:
    async with session.get('http://python.org') as response:
        print(await response.text())
    async with session.get('http://python.org/foobar') as response:
        print(await response.text())
   async with session.get('http://python.org/foo/foo/bar') as response:
        print(await response.text())

Write:

async with aiohttp.ClientSession(base_url='http://python.org') as session:
    async with session.get('/') as response:
        print(await response.text())
    async with session.get('/foobar') as response:
        print(await response.text())
   async with session.get('/foo/foo/bar') as response:
        print(await response.text())

Describe the solution you'd like

Add an base_url parameter to ClientSession, like httpx does.

Describe alternatives you've considered

An alternative is having a constant BASE = 'http://python.org' and then say:

async with session.get(f'{BASE}/foobar') as response:
        print(await response.text())

Related component

Client

Additional context

No response

Code of Conduct

  • I agree to follow the aio-libs Code of Conduct

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions