Python and APIs

In the modern programming world, APIs (Application Programming Interfaces) play a central role in enabling communication between applications and services. Python, with its clean syntax and powerful libraries, offers robust tools for both consuming external APIs and creating your own. This chapter dives deep into understanding APIs, using Python to interact with them, and building your own APIs using frameworks like Flask and FastAPI.

1. What Is an API?

An API allows different software systems to communicate with each other. Think of it as a contract between two applications — one provides a service (server), and the other consumes it (client).

Types of APIs:

  • REST (Representational State Transfer) – Most common type, stateless and uses HTTP
  • SOAP (Simple Object Access Protocol) – XML-based, used in legacy systems
  • GraphQL – Flexible querying, newer architecture

In this chapter, we focus on RESTful APIs using JSON data format.

2. Consuming APIs in Python Using requests

Python’s requests library is a simple, elegant tool for making HTTP requests.

Installation:

pip install requests

Making a GET Request:

import requests
response = requests.get("https://api.github.com/users/octocat")
print(response.status_code)
print(response.json())

Making a POST Request:

data = {"name": "John", "job": "Developer"}
response = requests.post("https://reqres.in/api/users", json=data)
print(response.json())

Handling Headers and Parameters:

headers = {"Authorization": "Bearer YOUR_TOKEN"}
params = {"limit": 10}
response = requests.get("https://api.example.com/data", headers=headers, params=params)

Error Handling:

if response.status_code == 200:
    print("Success!")
elif response.status_code == 404:
    print("Not Found!")
else:
    print("Something went wrong")

3. Working with JSON Data

Most modern APIs return data in JSON format.

Convert JSON to Python:

response = requests.get("https://api.example.com")
data = response.json()
print(data["name"])

Convert Python to JSON:

import json
data = {"city": "New York"}
json_data = json.dumps(data)

4. Authentication in APIs

Most APIs require authentication:

Types of Auth:

  • API Keys: Simple token in query or header
  • Bearer Tokens: Used in OAuth2
  • Basic Auth: Username/password base64 encoded

Example with Bearer Token:

headers = {"Authorization": "Bearer YOUR_API_TOKEN"}
requests.get("https://api.example.com", headers=headers)

5. Rate Limiting and Pagination

Rate Limiting:

APIs may restrict how many requests you can make per minute or day. Always check X-RateLimit-Remaining headers.

Pagination:

Data is often split across pages:

page = 1
while True:
    response = requests.get(f"https://api.example.com/users?page={page}")
    data = response.json()
    if not data["users"]:
        break
    process(data)
    page += 1

6. Building APIs with Flask

Flask is a micro web framework perfect for building lightweight REST APIs.

Installation:

pip install flask

Basic API Example:

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/hello', methods=['GET'])
def hello():
    return jsonify({"message": "Hello from Flask API"})

@app.route('/greet', methods=['POST'])
def greet():
    data = request.get_json()
    return jsonify({"message": f"Hello, {data['name']}!"})

if __name__ == '__main__':
    app.run(debug=True)

7. Building APIs with FastAPI

FastAPI is a modern, high-performance web framework designed for building APIs quickly and efficiently.

Installation:

pip install fastapi uvicorn

Example:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.get("/")
def read_root():
    return {"message": "Welcome to FastAPI"}

@app.post("/items/")
def create_item(item: Item):
    return {"item": item}

Run Server:

uvicorn filename:app --reload

8. Validating Data with Pydantic

FastAPI uses Pydantic to validate data models.

class User(BaseModel):
    name: str
    age: int

@app.post("/user")
def create_user(user: User):
    return user

If you send a string instead of an integer for age, FastAPI will automatically return a validation error.

9. Documentation with Swagger and ReDoc

FastAPI provides automatic docs:

  • Swagger UI: /docs
  • ReDoc: /redoc

No extra setup required. Based on function annotations and Pydantic models.

10. Testing Your API

Using requests:

r = requests.post("http://127.0.0.1:8000/items/", json={"name": "Book", "price": 12.99})
print(r.json())

Using Postman:

  • Set method to GET/POST
  • Add headers and body as needed
  • Hit Send

Using cURL:

curl -X POST http://localhost:8000/items/ -H "Content-Type: application/json" -d '{"name":"Book", "price":10.99}'

11. Error Handling in APIs

Always return meaningful error messages:

from fastapi import HTTPException

@app.get("/items/{item_id}")
def read_item(item_id: int):
    if item_id > 100:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item_id": item_id}

12. Security and Best Practices

  • Validate all input data
  • Use HTTPS for secure communication
  • Handle exceptions gracefully
  • Limit request rate
  • Keep API keys secret
  • Use environment variables for configs

13. Real-World Applications

  • Weather dashboards using OpenWeatherMap API
  • Stock market monitors using Alpha Vantage
  • Social media bots using Twitter/Facebook APIs
  • E-commerce apps with payment gateway APIs
  • Data pipelines integrating multiple APIs

14. Summary

APIs are the backbone of modern web and mobile applications. Python makes it easy to consume third-party APIs and build your own using frameworks like Flask and FastAPI. In this chapter, you:

  • Learned how to send GET and POST requests using requests
  • Understood authentication, pagination, and error handling
  • Built RESTful APIs with Flask and FastAPI
  • Validated data and documented APIs
  • Explored security tips and real-world use cases

Next Chapter: Working with Dates and Time in Python – Dive into Python’s datetime, calendar, and time modules.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top