Chapter 17: Working with APIs

APIs (Application Programming Interfaces) enable applications to communicate with each other. Python provides excellent libraries for consuming and building APIs, making it a go-to language for integrating and creating web services.


Consuming APIs with Python

Using the requests Library

The requests library simplifies HTTP requests and is widely used for interacting with REST APIs.

Installing requests:

pip install requests

Making GET and POST Requests:

import requests

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

# POST request
payload = {"title": "foo", "body": "bar", "userId": 1}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=payload)
print(response.json())

Handling Response Codes:

Working with Authentication

Many APIs require authentication using API keys or tokens.

Example:


Building APIs with Python

Using Flask for API Development

Flask is a lightweight framework suitable for creating APIs.

Example:

Using Django for API Development

Django REST Framework (DRF) extends Django for building APIs.

Installing DRF:

Creating an API with DRF:

  1. Add 'rest_framework' to INSTALLED_APPS in settings.py.

  2. Define a serializer in serializers.py:

  3. Create a view in views.py:

  4. Map the view to a URL in urls.py:


Advanced API Techniques

Pagination

Paginate API results to handle large datasets.

Rate Limiting

Use tools like Flask-Limiter to restrict API usage.

Error Handling

Provide meaningful error messages for invalid requests.


Exercises

Exercise 1: Consume a Public API

Fetch and display weather data using a public API like OpenWeatherMap.

Solution:

Exercise 2: Build a CRUD API with Flask

Create an API to manage a list of tasks with endpoints for adding, viewing, updating, and deleting tasks.

Solution:

Exercise 3: Build an API with Django REST Framework

Build a REST API for managing products using Django REST Framework.


Best Practices

  1. Documentation: Use tools like Swagger or Postman to document APIs.

  2. Authentication: Secure APIs with OAuth, API keys, or JWTs.

  3. Validation: Validate request data to prevent errors and abuse.

  4. Error Handling: Return descriptive error messages with appropriate HTTP status codes.

  5. Testing: Write unit tests to ensure API reliability.

In the next chapter, we will explore automation with Python, including automating tasks like file handling, web scraping, and system monitoring.

Last updated