In modern web development, the frontend-backend separation architecture has become increasingly common, and RESTful APIs are the core bridge for data interaction between the frontend and backend. Simply put, a RESTful API is an interface designed following the REST (Representational State Transfer) style through the HTTP protocol, used to transfer data between the client and the server. This article will start from basic concepts and guide you to implement a simple GET data interface using the Flask framework, suitable for programming beginners to get started quickly.
1. What is a RESTful API?¶
A RESTful API is a software architecture style used to create scalable and maintainable web services. Its core features include:
- Resource-centered: The interface is designed around “resources” (e.g., users, products, orders), with each resource identified by a unique URL (e.g., /users represents the user resource).
- Clear HTTP methods: Standard HTTP methods (GET, POST, PUT, DELETE) are used to represent operations on resources:
- GET: Retrieve resources (e.g., querying a user list).
- POST: Create resources (e.g., adding a new user).
- PUT: Update resources (e.g., modifying user information).
- DELETE: Delete resources (e.g., removing a user).
- Stateless: The server does not store client state information; each request is independent and complete.
- Return JSON format: Typically returns JSON data for easy parsing by the client.
2. Why Choose Flask?¶
Flask is a lightweight Python web framework that:
- Simple and flexible: A gentle learning curve, ideal for beginners to get started quickly.
- Highly extensible: Its basic functionality is concise, with extensibility via plugins (e.g., database connections, authentication).
- Minimal code: No complex configuration is needed; a few lines of code can implement a basic interface.
3. Install Flask¶
Use Python’s package manager pip to install Flask:
pip install flask
If you need a virtual environment to isolate dependencies, you can create one first (optional):
python -m venv myenv # Create a virtual environment
source myenv/bin/activate # On Windows: myenv\Scripts\activate
pip install flask
4. Implement Your First GET Interface¶
We will implement it in two steps: first, a simple “greeting” interface, then a practical “get user list” interface.
1. Simple Greeting Interface¶
Goal: When accessing the / path, return “Hello, Flask!”.
Code Example:
from flask import Flask
# Initialize Flask application
app = Flask(__name__)
# Define route: When accessing the / path, execute the hello function
@app.route('/')
def hello():
return "Hello, Flask!" # Return a string
# Run the application
if __name__ == '__main__':
app.run(debug=True) # debug=True: Development mode, auto-reload code
Key Explanations:
- app = Flask(__name__): Creates a Flask application instance. __name__ is a built-in Python variable representing the current module name, used to locate resource paths.
- @app.route('/'): Route decorator that defines the access path as /. When a user accesses this path, the following hello function is executed.
- return "Hello, Flask!": The function returns a string, which Flask automatically converts into an HTTP response body.
- app.run(debug=True): Starts the web server. debug=True enables development mode (auto-restart on code changes, with detailed error messages).
2. Advanced: User List Interface Returning JSON Data¶
Goal: When accessing the /users path, return a JSON array containing user information.
Code Example:
from flask import Flask, jsonify # Import jsonify to return JSON
app = Flask(__name__)
# Simulate database data (in actual projects, read from a database)
users = [
{"id": 1, "name": "Alice", "age": 25, "email": "alice@example.com"},
{"id": 2, "name": "Bob", "age": 30, "email": "bob@example.com"},
{"id": 3, "name": "Charlie", "age": 28, "email": "charlie@example.com"}
]
# Define GET interface: /users
@app.route('/users', methods=['GET']) # methods specifies allowed HTTP methods (default: only GET)
def get_users():
return jsonify(users) # jsonify automatically converts the list to JSON and sets Content-Type
if __name__ == '__main__':
app.run(debug=True, port=5000) # port=5000: Specify port (default 5000, customizable)
Key Explanations:
- jsonify(users): Converts the Python list users into a JSON-formatted response body and sets the HTTP response header Content-Type: application/json to avoid parsing errors on the client side.
- methods=['GET']: Explicitly declares that the interface only accepts GET requests (implicitly allowed by default, but explicit declaration is clearer).
5. Run and Test the Interface¶
1. Start the Application¶
Execute in the directory where the code file (e.g., app.py) is located:
python app.py
The console output will be similar to:
* Serving Flask app 'app'
* Debug mode: on
* Running on http://127.0.0.1:5000 (Press CTRL+C to quit)
This indicates the application has started on the local port 5000.
2. Test the Interface¶
- Browser access: Open a browser and enter
http://localhost:5000/usersto see the returned user list JSON data. - Command-line test: Use the
curlcommand:
curl http://localhost:5000/users
- Postman test: Open Postman, select the
GETmethod, enterhttp://localhost:5000/users, and click “Send” to view the result.
6. Summary¶
Through this article, you have mastered the core steps to implement a simple GET interface with Flask:
1. Import Flask and jsonify (if returning JSON).
2. Initialize the Flask application.
3. Define routes and HTTP methods using @app.route.
4. Write functions to return data (strings or JSON).
5. Start the service with app.run().
Next steps for extension:
- Add more routes (e.g., /users/<user_id> to get a single user).
- Integrate a database (e.g., use SQLAlchemy to connect to MySQL/PostgreSQL).
- Implement other HTTP methods (e.g., POST to create a user).
Flask’s flexibility allows you to quickly transition from entry-level to advanced development. Happy coding!