Python
  • Intro.
  • Catalogue
  • Chapter 1: Introduction to Python
  • Chapter 2: Python Syntax and Fundamentals
    • Chapter: Variables and Data Types in Python
  • Chapter 3: Control Flow
  • Chapter 4: Functions
  • Chapter 5: Data Structures
  • Chapter 6: Object-Oriented Programming (OOP)
  • Chapter 7: Modules and Packages
  • Chapter 8: File Handling
  • Chapter 9: Error and Exception Handling
  • Chapter 10: Working with Databases
  • Chapter 11: Iterators and Generators
  • Chapter 12: Decorators and Context Managers
  • Chapter 13: Concurrency and Parallelism
  • Chapter 14: Testing and Debugging
  • Chapter 15: Web Development with Python
  • Chapter 16: Data Science and Machine Learning with Python
  • Chapter 17: Working with APIs
  • Chapter 18: Automation with Python
  • Chapter 19: Python and Cloud/DevOps
  • Chapter 20: Python and IoT
  • Appendices
Powered by GitBook
On this page

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:

if response.status_code == 200:
    print("Success:", response.json())
elif response.status_code == 404:
    print("Not Found")

Working with Authentication

Many APIs require authentication using API keys or tokens.

Example:

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

Building APIs with Python

Using Flask for API Development

Flask is a lightweight framework suitable for creating APIs.

Example:

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route("/api/data", methods=["GET"])
def get_data():
    return jsonify({"message": "Hello, World!"})

@app.route("/api/data", methods=["POST"])
def post_data():
    data = request.json
    return jsonify({"received": data})

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

Using Django for API Development

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

Installing DRF:

pip install djangorestframework

Creating an API with DRF:

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

  2. Define a serializer in serializers.py:

    from rest_framework import serializers
    
    class ItemSerializer(serializers.Serializer):
        id = serializers.IntegerField()
        name = serializers.CharField(max_length=100)
  3. Create a view in views.py:

    from rest_framework.views import APIView
    from rest_framework.response import Response
    
    class ItemView(APIView):
        def get(self, request):
            data = [
                {"id": 1, "name": "Item 1"},
                {"id": 2, "name": "Item 2"}
            ]
            return Response(data)
  4. Map the view to a URL in urls.py:

    from django.urls import path
    from .views import ItemView
    
    urlpatterns = [
        path('api/items/', ItemView.as_view(), name='item-list'),
    ]

Advanced API Techniques

Pagination

Paginate API results to handle large datasets.

@app.route("/api/items", methods=["GET"])
def get_items():
    page = int(request.args.get("page", 1))
    per_page = int(request.args.get("per_page", 10))
    items = [f"Item {i}" for i in range(1, 101)]  # Sample data
    start = (page - 1) * per_page
    end = start + per_page
    return jsonify(items[start:end])

Rate Limiting

Use tools like Flask-Limiter to restrict API usage.

pip install flask-limiter
from flask import Flask
from flask_limiter import Limiter

app = Flask(__name__)
limiter = Limiter(app, key_func=lambda: "user_key")

@app.route("/api/data")
@limiter.limit("5 per minute")
def limited_data():
    return {"message": "Limited access"}

Error Handling

Provide meaningful error messages for invalid requests.

@app.errorhandler(404)
def not_found(error):
    return jsonify({"error": "Not Found"}), 404

Exercises

Exercise 1: Consume a Public API

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

Solution:

import requests

API_KEY = "your_api_key"
url = f"http://api.openweathermap.org/data/2.5/weather?q=London&appid={API_KEY}"
response = requests.get(url)
print(response.json())

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:

from flask import Flask, jsonify, request

app = Flask(__name__)
tasks = []

@app.route("/tasks", methods=["GET"])
def get_tasks():
    return jsonify(tasks)

@app.route("/tasks", methods=["POST"])
def add_task():
    task = request.json
    tasks.append(task)
    return jsonify(task), 201

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

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.

PreviousChapter 16: Data Science and Machine Learning with PythonNextChapter 18: Automation with Python

Last updated 5 months ago