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 requestsMaking 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:
Add
'rest_framework'toINSTALLED_APPSinsettings.py.Define a serializer in
serializers.py:Create a view in
views.py: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
Documentation: Use tools like Swagger or Postman to document APIs.
Authentication: Secure APIs with OAuth, API keys, or JWTs.
Validation: Validate request data to prevent errors and abuse.
Error Handling: Return descriptive error messages with appropriate HTTP status codes.
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