Python APIs: Consume & Build RESTful Services
Learn to interact with web services and create your own APIs!
1. What Are APIs & REST?
API (Application Programming Interface): A messenger that allows two applications to communicate (e.g., fetch weather data from a server).
REST (REpresentational State Transfer): A standard architecture for building web services using HTTP methods (GET, POST, PUT, DELETE).
Analogy: Think of an API as a restaurant menu – you (client) order dishes (data) from the kitchen (server) using a predefined list (endpoints).
2. Consuming APIs with requests
Installation
pip install requests
Example 1: GET Request (Fetch Data)
import requests
# Fetch posts from JSONPlaceholder API
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
if response.status_code == 200:
data = response.json()
print(f"Title: {data['title']}\nBody: {data['body']}")
else:
print(f"Error: {response.status_code}")
Output:
Title: sunt aut facere...
Body: quia et suscipit...
Example 2: POST Request (Send Data)
new_post = {
"title": "My New Post",
"body": "Learning Python APIs!",
"userId": 1
}
response = requests.post(
"https://jsonplaceholder.typicode.com/posts",
json=new_post
)
print(response.json()) # Returns created post with ID
Key Concepts:
- Headers: Pass metadata (e.g.,
headers={"Authorization": "Bearer TOKEN"}
). - Parameters: Filter data via URL params (
params={"userId": 1}
). - Authentication: Use API keys, OAuth, etc.
3. Building APIs with Flask
Installation
pip install flask
Basic REST API (Todo List)
from flask import Flask, jsonify, request
app = Flask(__name__)
# In-memory database
todos = [
{"id": 1, "task": "Learn Flask", "done": False}
]
# GET all todos
@app.route("/todos", methods=["GET"])
def get_todos():
return jsonify({"todos": todos})
# POST a new todo
@app.route("/todos", methods=["POST"])
def add_todo():
new_todo = request.json
new_todo["id"] = len(todos) + 1
todos.append(new_todo)
return jsonify(new_todo), 201
# GET single todo
@app.route("/todos/", methods=["GET"])
def get_todo(todo_id):
todo = next((t for t in todos if t["id"] == todo_id), None)
return jsonify(todo) if todo else ("Not found", 404)
if __name__ == "__main__":
app.run(debug=True)
Test with curl or Postman:
# GET all todos
curl http://localhost:5000/todos
# POST a new todo
curl -X POST -H "Content-Type: application/json" -d '{"task":"Build API"}' http://localhost:5000/todos
4. Real-World Use Cases
Consuming APIs:
- Fetch weather data from OpenWeatherMap.
- Integrate payment gateways like Stripe.
- Analyze tweets with Twitter API.
Building APIs:
- Backend for mobile apps.
- Microservices architecture.
- Data dashboard for IoT devices.
Key Concepts
HTTP Methods:
Method | Purpose |
---|---|
GET | Retrieve data |
POST | Create new data |
PUT | Update existing data |
DELETE | Remove data |
Status Codes:
200 OK
: Success.201 Created
: Resource created.400 Bad Request
: Invalid input.404 Not Found
: Resource doesn’t exist.500 Internal Server Error
: Server error.
Best Practices
- Versioning: Prefix endpoints with
/api/v1/....
. - Validation: Check incoming data (e.g.,
if "task" not in request.json
). - Rate Limiting: Prevent abuse with
flask-limiter
. - Documentation: Use tools like Swagger/OpenAPI.
- Security: Use HTTPS, JWT tokens, and sanitize inputs.
Example: Weather API Consumer
def get_weather(city):
API_KEY = "your_api_key"
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}"
response = requests.get(url)
data = response.json()
return {
"temp": data["main"]["temp"] - 273.15, # Kelvin to Celsius
"description": data["weather"][0]["description"]
}
print(get_weather("London"))
Comparison: Consuming vs. Building APIs
Aspect | Consuming APIs | Building APIs |
---|---|---|
Tools | requests | Flask/Django, jsonify |
Purpose | Fetch external data | Expose data/services |
Complexity | Moderate | High (security, scaling) |
Key Takeaways
- ✅ Consume APIs: Use
requests
to interact with external services. - ✅ Build APIs: Use Flask to create RESTful endpoints.
- ✅ Follow Standards: Use proper HTTP methods, status codes, and JSON.
What’s Next?
Learn authentication (JWT, OAuth) and deployment (Docker, Heroku) for production-ready APIs!
Tags:
python