async get
- Python course
- Advanced
- Lesson 39/83
- 5 min
Learn GET requests with await session.get.
async get
session.get(url) is the asynchronous method that makes a GET request. The response is returned as a context manager and opened with async with.
async with session.get("https://example.com") as resp:
text = await resp.text()resp.status gives the status code and resp.text() gives the body. The body is a coroutine, so it is awaited with await.
Status code and body
A GET response has two key pieces of data: the status code (e.g. 200, 404) and the body. The status code comes from the resp.status attribute, the body from await resp.text() or await resp.read().
async with session.get(url) as resp:
print(resp.status)
print(await resp.text())200 means success, 404 means not found, 500 means server error. You can read the body once; a second read returns empty.
Practice Read body with async get
Start with import asyncio and import aiohttp. Inside async def main() open async with aiohttp.ClientSession() as session:. Make a GET request with async with session.get("https://example.com") as resp:. Print the body with print(await resp.text()). Add asyncio.run(main()).
Starter code
# load asyncio and aiohttp
# open a session with async with
# make a get request on the session
# read the body with await and print it
# run main with asyncio.runSample solution
import asyncio
import aiohttp
class _S:
async def __aenter__(self): return self
async def __aexit__(self, *a): return False
def get(self, url): return self
async def text(self): return 'merhaba'
aiohttp.ClientSession = _S
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('https://example.com') as resp:
print(await resp.text())
asyncio.run(main())Expected output
merhaba
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the get concepts
| Term | Meaning |
|---|---|
session.get |
Makes a GET request |
resp.status |
Gives status code |
await resp.text |
Returns body |
async with |
Closes resource |
2 What does session.get(url) return?
- A context manager Correct answer
- A dict
- A string
- A file object
Explanation: session.get returns a context manager; it is opened with async with.
3 Complete the get call
async with ____("https://example.com") as resp:
async with session.get("https://example.com") as resp:
Explanation: session.get(url) makes a GET request.