Manually testing APIs or fetching data through a browser gets tedious fast. That’s where Python’s requests library shines. With just a few lines of code, you can programmatically interact with REST APIs—fetching data, creating records, updating entries, or deleting them—all without touching Postman.
Setting Up
First, ensure you have Python installed. Fire up your terminal and install the requests library:
bash
Copy
Download
pip install requests
We’ll use the GoRest API for this walkthrough. You’ll need an access token (sign in via Google to get one). Treat this token like a password—keep it secure!
Pro Tip:
Store sensitive tokens as environment variables instead of hardcoding them:
python
Copy
Download
import os
auth_token = os.getenv(“GOREST_TOKEN”) # Safer than pasting directly
Making API Calls
1. Fetching Data (GET Request)
Want to retrieve user data? Here’s how:
python
Copy
Download
import requests
import json
base_url = “https://gorest.co.in/public/v2”
def fetch_users():
url = f”{base_url}/users”
headers = {“Authorization”: f”Bearer {auth_token}”}
response = requests.get(url, headers=headers)
response.raise_for_status() # Crash loudly if the request fails
users = response.json()
print(json.dumps(users, indent=2)) # Pretty-print JSON
fetch_users()
Expected Output: A neatly formatted list of users.
2. Creating Records (POST Request)
Need to add a new user? Define the payload and shoot a POST request:
python
Copy
Download
def create_user():
url = f”{base_url}/users”
headers = {“Authorization”: f”Bearer {auth_token}”}
new_user = {
“name”: “Alex Techton”,
“email”: “[email protected]”,
“gender”: “male”,
“status”: “active”
}
response = requests.post(url, json=new_user, headers=headers)
if response.status_code == 201:
print(“User created! ID:”, response.json()[“id”])
else:
print(“Failed:”, response.text)
create_user()
Verify: Check the GoRest dashboard—your new user should appear.
3. Updating Entries (PUT Request)
Misspelled a name? Update it:
python
Copy
Download
def update_user(user_id):
url = f”{base_url}/users/{user_id}”
headers = {“Authorization”: f”Bearer {auth_token}”}
updates = {“name”: “Alexander Techton”, “status”: “inactive”}
response = requests.put(url, json=updates, headers=headers)
print(“Update successful!” if response.ok else “Failed:”, response.text)
# Usage: Pass the user ID from the POST response
update_user(1234)
4. Deleting Records (DELETE Request)
Time to clean up? Deleting is straightforward:
python
Copy
Download
def delete_user(user_id):
url = f”{base_url}/users/{user_id}”
headers = {“Authorization”: f”Bearer {auth_token}”}
response = requests.delete(url, headers=headers)
if response.status_code == 204:
print(f”User {user_id} deleted.”)
else:
print(“Error:”, response.status_code)
# Usage: Delete the user created earlier
delete_user(1234)
Handling Edge Cases
- Rate Limiting: APIs often throttle requests. Slow down with time.sleep(1) between calls.
- Error Handling: Use try-except blocks to manage timeouts or invalid responses.
- Pagination: For large datasets, loop through pages using query params like ?page=2.
Why This Matters
Automating API interactions isn’t just for developers. Marketers can sync CRM data, analysts can scrape public datasets, and QA teams can run regression tests—all without manual clicks.
Next Steps:
- Explore authenticated APIs (OAuth2, API keys).
- Mock APIs for testing with pytest and responses.
- Build a CLI tool to manage API workflows.
Grab your token, tweak the snippets, and start automating. Your keyboard (and sanity) will thank you.
Note: Replace placeholder tokens and IDs with your actual values. Always check API docs for endpoint changes.