// plain
Using Python Aiohttp, you can get JSON data from a web server.
import aiohttp
async def fetch(session, url):
async with session.get(url) as response:
return await response.json()
async def main():
async with aiohttp.ClientSession() as session:
json_data = await fetch(session, 'https://example.com/data.json')
print(json_data)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
{
"name": "John Doe",
"age": 34
}
import aiohttp
- imports the aiohttp libraryasync def fetch(session, url)
- defines an asynchronous function to fetch the JSON data from the given URLasync with session.get(url) as response
- uses the session to make a GET request to the given URLreturn await response.json()
- returns the response as JSONasync def main()
- defines an asynchronous function to run the codeasync with aiohttp.ClientSession() as session
- creates a client session to make the requestjson_data = await fetch(session, 'https://example.com/data.json')
- calls thefetch
function to get the JSON data from the given URLprint(json_data)
- prints the JSON dataloop = asyncio.get_event_loop()
- creates an event looploop.run_until_complete(main())
- runs themain
function until it is complete
group: aiohttp
onelinerhub: How to get JSON data using Python Aiohttp?