Working with APIs
Section 8: Working with APIs
Lesson 1: Consuming APIs
1.1 Making HTTP Requests with Python
Python provides several libraries for making HTTP requests. One commonly used library is requests.
Example:
# Making HTTP requests with Python (using requests)
import requests
# Making a GET request
response = requests.get("https://jsonplaceholder.typicode.com/todos/1")
# Displaying the response content
print(response.text)
1.2 Parsing JSON Responses
Many APIs return data in JSON format. Python's json module can be used to parse JSON responses.
Example:
# Parsing JSON responses
import requests
import json
# Making a GET request
response = requests.get("https://jsonplaceholder.typicode.com/todos/1")
# Parsing JSON
data = json.loads(response.text)
# Accessing specific data
title = data['title']
print("Title:", title)
Lesson 2: Building APIs with Flask
2.1 Creating a Simple RESTful API
Flask can be used to build APIs easily. A simple example of a RESTful API with Flask is provided below.
Example:
# Building APIs with Flask
from flask import Flask, jsonify
app = Flask(__name__)
# Sample data
todos = [
{'id': 1, 'title': 'Buy groceries', 'done': False},
{'id': 2, 'title': 'Read a book', 'done': True}
]
# Endpoint for getting all todos
@app.route('/todos', methods=['GET'])
def get_todos():
return jsonify({'todos': todos})
if __name__ == '__main__':
app.run(debug=True)
In this example, a simple API is created with a single endpoint /todos that returns a list of todos in JSON format.
In Section 8, we explored working with APIs, both consuming external APIs and building APIs using Flask.
Consuming APIs involves making HTTP requests using Python, often through the requests library, and parsing JSON responses. This allows you to retrieve and use data from various online services.
Building APIs with Flask allows you to expose your own data or services through a RESTful API. Flask simplifies the process of creating endpoints and handling requests and responses.
Understanding how to work with APIs is crucial for integrating external services into your applications and exposing your own services for others to consume. As you gain more experience, you can explore more advanced topics such as authentication, error handling, and working with different types of APIs (RESTful, SOAP, GraphQL).