python-aiohttpHow to make a GET request with Python Aiohttp?
Making a GET request with Python Aiohttp is easy and straightforward.
import aiohttp
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'http://python.org')
print(html)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
The output of the example code will be the HTML content of the page http://python.org.
Code explanation
import aiohttp
- imports the aiohttp libraryasync def fetch(session, url)
- defines an asynchronous function to make a GET requestasync with session.get(url) as response
- makes a GET request to the specified URLreturn await response.text()
- returns the response as textasync with aiohttp.ClientSession() as session
- creates a client sessionhtml = await fetch(session, 'http://python.org')
- calls the fetch function to make a GET requestprint(html)
- prints the responseloop = asyncio.get_event_loop()
- creates an event looploop.run_until_complete(main())
- runs the main function until it is complete
Helpful links
Related
- How to handle x-www-form-urlencoded with Python Aiohttp?
- How to create a websocket server using Python Aiohttp?
- How to create a JSON response using Python Aiohttp?
- How to disable SSL verification in Python Aiohttp?
- How to create a connection pool with Python Aiohttp?
- How to check if a session is closed with Python Aiohttp?
- How to create a server with Python Aiohttp?
- How to reuse a session with Python Aiohttp?
- How to close a Python Aiohttp session?
- How to rate limit with Python Aiohttp?
More of Python Aiohttp
- How to handle x-www-form-urlencoded with Python Aiohttp?
- How to create a websocket server using Python Aiohttp?
- How to create a JSON response using Python Aiohttp?
- How to reuse a session with Python Aiohttp?
- Bearer token request example with Python Aiohttp?
- How to rate limit with Python Aiohttp?
- How to redirect with Python Aiohttp?
- How to get response text with Python Aiohttp?
- How to retry a request with Python Aiohttp?
- How to make parallel requests with Python Aiohttp?
See more codes...