Summary - HTTP and aiohttp
- Python course
- Advanced
- Lesson 42/83
- 5 min
Combine ClientSession, get and json to write a weather client.
Summary - HTTP and aiohttp
In this group you learned HTTP requests. With urllib.request you make synchronous requests; with aiohttp.ClientSession you make asynchronous ones. session.get and session.post give different request types; await resp.text() gives the body; json.loads parses structured data.
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
data = json.loads(await resp.text())In the final step you will combine all of these to write a weather client.
Practice Weather client
Start with import asyncio, import aiohttp and import json. 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:. Get the body with text = await resp.text(). Turn it into a dict with data = json.loads(text). Print the city with print(data["sehir"]). Add asyncio.run(main()).
Starter code
# load asyncio, aiohttp and the structured-data module
# open a session with async with
# make a get request on the session
# read the body with await and parse with the loads function
# print the city from the dict
# run main with asyncio.runSample solution
import asyncio
import aiohttp
import json
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 '{"sehir": "İstanbul"}'
aiohttp.ClientSession = _S
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('https://example.com') as resp:
text = await resp.text()
data = json.loads(text)
print(data['sehir'])
asyncio.run(main())Expected output
İstanbul
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which function parses the response body as structured data?
- urlopen
- json.loads Correct answer
- session.get
- asyncio.run
Explanation: json.loads(string) turns structured data into a dict.
2 Match the group tools
| Term | Meaning |
|---|---|
urllib.request |
Synchronous request |
aiohttp.ClientSession |
Async session |
session.get |
GET request |
json.loads |
Parses structured data |