When writing Python code that interacts with other systems and APIs, you'll likely need to make HTTP requests to send or receive data. Python provides several libraries to handle different types of requests. In this article, we'll give an overview of the main options.
Sending Basic Requests
For basic HTTP requests, the
import requests
response = requests.get('https://api.example.com/data')
print(response.text)
And a POST request:
import requests
data = {'key': 'value'}
response = requests.post('https://api.example.com/data', data=data)
The
Asynchronous Requests
Sometimes you may want to send multiple requests simultaneously and process the responses as they complete instead of waiting for each one to finish. This is where
import asyncio
import aiohttp
async def get_data(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
# Send 3 requests concurrently
urls = ['https://url1.com', 'https://url2.com', 'https://url3.com']
loop = asyncio.get_event_loop()
futures = [loop.run_in_executor(None, get_data, url) for url in urls]
for response in await asyncio.gather(*futures):
print(response)
The key difference is that instead of waiting for each request to complete, the requests are fired off simultaneously.
Framework-Level Requests
If you're building a web application with a framework like Django or Flask, the framework will have its own request handling built-in. For example, in Flask you can access the incoming HTTP request data through the global