Python is often used to interact with external APIs for monitoring, integration, analytics, or automation. To do this competently and safely, it is important to use virtual environments and properly configure cyclic HTTP requests.
In this article we will analyze:
- creating a virtual environment;
- installing popular HTTP clients;
- developing typical API requests.
Creating and activating an environment
To do this, go to the project or create a directory where we will install the environment using the module.:
python3 -m venv venv
To activate the environment, specify:
Linux/macOS:
Windows:
Installing HTTP libraries
Fix the dependencies:
Examples of HTTP requests
1. requests (synchronous client)
response = requests.get("https://api.github.com")
print(response.status_code)
print(response.json())
2. httpx (synchronous and asynchronous)
response = httpx.get("https://api.github.com")
print(response.status_code)
Asynchronous version:
import asyncio
async def main():
async with httpx.AsyncClient() as client:
resp = await client.get("https://api.github.com")
print(resp.status_code)
asyncio.run(main())
Cyclic queries based on data from a file
Let's say we have a list of IDs that we need to make API requests with. The script looks like this:
📁 input.txt
123
456
abc
🧠 main.py full example
import time
API_URL = "https://api.example.com/data /" # Replace with a real URL
HEADERS = {
"Authorization": "Bearer YOUR_API_TOKEN",
"Content-Type": "application/json"
}
with open("input.txt", "r") as f:
values = [line.strip() for line in f if line.strip()]
for val in values:
try:
url = f"{API_URL}{val}"
response = requests.get(url, headers=HEADERS, timeout=10)
if response.status_code == 200:
print(f"[✓] {val}: Successful")
print(response.json())
else:
print(f"[!] {val}: Status {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"[✗] {val}: Error — {e}")
time.sleep(1) # We are not overloading the API
The script:
1. Reads lines from a file input.txt (for example, IDs or codes);
2. Substitutes each line in the API URL;
3. Sends a GET request;
4. Processes the response;
5. Pauses between requests so as not to overload the server.
Working with HTTP in Python is easy if you use a virtual environment, manage dependencies correctly, monitor errors and request frequency, and process input data from files.