DEV Community

Phil IPS
Phil IPS

Posted on

Testing Free API Endpoints with Python

Testing Free API Endpoints with Python

Learn how to test free public APIs using Python's requests library. No API keys required!

Prerequisites

  • Python 3.8+ installed
  • requests library: pip install requests

Testing JSONPlaceholder API

JSONPlaceholder is a free fake REST API for testing and prototyping.

import requests

# Test GET request
url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)

if response.status_code == 200:
    data = response.json()
    print(f"Title: {data['title']}")
    print(f"Body: {data['body']}")
else:
    print(f"Error: {response.status_code}")
Enter fullscreen mode Exit fullscreen mode

Testing a Free Weather API

OpenWeatherMap offers a free tier for weather data.

import requests

# Free API (no key required for basic usage)
url = "https://api.open-meteo.com/v1/forecast"
params = {
    "latitude": 51.5074,
    "longitude": -0.1278,
    "current_weather": True
}

response = requests.get(url, params=params)

if response.status_code == 200:
    weather = response.json()["current_weather"]
    print(f"Temperature: {weather['temperature']}°C")
    print(f"Wind Speed: {weather['windspeed']} km/h")
else:
    print(f"Error: {response.status_code}")
Enter fullscreen mode Exit fullscreen mode

Testing Free AI Model via OpenRouter

import requests
import os

# Using OpenRouter free tier
url = "https://openrouter.ai/api/v1/chat/completions"
headers = {
    "Authorization": f"Bearer {os.getenv('OPENROUTER_API_KEY')}",
    "Content-Type": "application/json"
}
data = {
    "model": "google/gemini-2.0-flash-exp:free",
    "messages": [{"role": "user", "content": "Explain REST APIs in 2 sentences"}]
}

response = requests.post(url, headers=headers, json=data)

if response.status_code == 200:
    result = response.json()
    print(result["choices"][0]["message"]["content"])
else:
    print(f"Error: {response.status_code} - {response.text}")
Enter fullscreen mode Exit fullscreen mode

Best Practices

  1. Always check status codes - Handle 200, 404, 429, 500 appropriately
  2. Add timeouts - requests.get(url, timeout=10)
  3. Handle rate limits - Implement exponential backoff
  4. Validate responses - Check JSON structure before accessing keys
  5. Use environment variables - Never hardcode API keys

Conclusion

Testing free APIs is a great way to learn API integration without costs. Start with JSONPlaceholder for REST basics, then explore weather, AI, and other free tiers for real-world projects.

Top comments (0)