python-aiohttpHow to get JSON data using Python Aiohttp?
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
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 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 download large files with Python Aiohttp?
- How to redirect with Python Aiohttp?
- How to use Gzip 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 use HTTP2 with Python Aiohttp?
- How to redirect with Python Aiohttp?
- How to create a JSON response using Python Aiohttp?
- How to get response text with Python Aiohttp?
- How to set headers in 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?
See more codes...