Building and Using RESTful APIs with Python
Hello everyone, I am Xiao Ai! Today we are going to explore a super useful skill in Python – RESTful API. Simply put, an API acts like a “microphone” between two programs, and a RESTful API is a particularly popular way of communicating. By mastering this, you can enable different programs to exchange data!
Sounds cool, right? Don’t worry, Xiao Ai will guide you step by step in the simplest way to master the use and creation of APIs. By the end of today’s content, you will be able to call APIs to retrieve data and even set up a simple API service!
1. What is an API?
API (Application Programming Interface) is the “bridge” between applications, defining how programs communicate with each other. A RESTful API is a special design style that:
- Uses HTTP protocol for communication
- Is centered around resources (like users, products)
- Operates on resources through HTTP methods (GET, POST, etc.)
Imagine an API as a restaurant waiter: you (the client) tell the waiter (the API) what you want, and the waiter goes to the kitchen (the server) to bring you the food (data)~
2. Calling an API with Python
Let’s start with the simplest example: using Python to request data from a public weather API.
1. Install the requests library
pip install requests
2. Call the weather API
import requests
# Call the free weather API
response = requests.get('https://api.openweathermap.org/data/2.5/weather?q=Beijing&appid=your_API_key')
# Check the returned data
print(response.status_code) # Status code, 200 means success
print(response.json()) # Returned JSON data
Code Explanation:
<span>requests.get()</span>
: Sends a GET request<span>response.json()</span>
: Converts the returned data into a Python dictionary
Tips:
- You need to register at OpenWeatherMap to get a free API key
- Remember to replace
<span>your_API_key</span>
in the code with your actual key
3. Understanding HTTP Methods
RESTful APIs use different HTTP methods to operate on resources:
Method | Purpose | Example |
---|---|---|
GET | Retrieve resources | Get user information |
POST | Create resources | Create a new user |
PUT | Update entire resources | Update all user information |
PATCH | Update partial resources | Only update user phone number |
DELETE | Delete resources | Delete a user |
4. Creating a Simple API with Flask
Now let’s create our own API service using Python’s Flask framework!
1. Install Flask
pip install flask
2. Create the API service
Create a new <span>app.py</span>
file:
from flask import Flask, jsonify, request
app = Flask(__name__)
# Simulate some data
books = [
{"id": 1, "title": "Introduction to Python", "author": "Xiao Ai"},
{"id": 2, "title": "Flask Guide", "author": "Reverse Love"}
]
# Get all books (GET /books)
@app.route('/books', methods=['GET'])
def get_books():
return jsonify(books)
# Add new book (POST /books)
@app.route('/books', methods=['POST'])
def add_book():
new_book = request.get_json()
books.append(new_book)
return jsonify(new_book), 201
if __name__ == '__main__':
app.run(debug=True)
3. Run and Test the API
python app.py
Then test your API using Postman or curl:
- GET
<span>http://127.0.0.1:5000/books</span>
to get all books - POST
<span>http://127.0.0.1:5000/books</span>
to add a new book
5. Handling API Errors
A good API should handle errors properly:
# Get specific book (GET /books/<id>)
@app.route('/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
book = next((b for b in books if b['id'] == book_id), None)
if book:
return jsonify(book)
return jsonify({"error": "Book not found"}), 404
Code Explanation:
- If the book is found, return the book information
- If not found, return a 404 error and a message
6. Practical Application Scenarios
Once you learn about APIs, you can:
- Develop backend services for mobile apps
- Create systems with microservices architecture
- Integrate third-party services (payments, maps, etc.)
- Build web applications with separated front and back ends
Considerations:
- In production environments, consider authentication (like JWT)
- Important APIs should have access restrictions
- The format of returned data should be uniformly standardized
Conclusion
Today we learned:✅ What RESTful APIs are and their uses✅ How to use Python to call third-party APIs✅ The different roles of HTTP methods✅ How to create your own API service with Flask✅ Basic error handling methods
Students, that’s all for today’s Python learning journey! Did you learn something? Try creating an API to manage movie information, and feel free to ask Xiao Ai in the comments if you have any questions. Happy learning!
Mini Exercise:
- Extend the book API to add PUT and DELETE methods
- Try calling a free news API to retrieve data