52. Creating a REST API with Flask
Here are 10 Python code snippets demonstrating how to create a simple REST API with Flask, covering various aspects of building a RESTful web service:
1. Basic Flask REST API Setup
A basic Flask setup with a simple route.
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api', methods=['GET'])
def api_home():
return jsonify({"message": "Welcome to the API!"})
if __name__ == '__main__':
app.run(debug=True)This simple API responds with a JSON message at the /api route.
2. Handling GET Requests
Returning data in JSON format from a GET request.
from flask import Flask, jsonify
app = Flask(__name__)
data = {
"user": "Alice",
"age": 25
}
@app.route('/api/user', methods=['GET'])
def get_user():
return jsonify(data)
if __name__ == '__main__':
app.run(debug=True)The API returns the data dictionary as JSON when accessed via the /api/user route.
3. Handling POST Requests
Accepting JSON data and responding accordingly.
This snippet allows clients to send JSON data via a POST request and get a response with the data.
4. Handling PUT Requests
Updating resources via PUT requests.
This API allows updating an existing user’s data via a PUT request.
5. Handling DELETE Requests
Deleting a resource via a DELETE request.
The /api/user route handles a DELETE request to remove the user data.
6. Query Parameters in GET Requests
Using query parameters to filter results.
This example accepts a query parameter name to customize the greeting message.
7. Handling URL Parameters
Extracting parameters from the URL.
Here, the name parameter is extracted directly from the URL and used in the response.
8. Returning Status Codes
Returning appropriate HTTP status codes in responses.
This snippet demonstrates how to return a 404 status code with a message.
9. Flask API with Authentication (Basic Auth)
Securing API routes with basic authentication.
This route requires basic authentication using the Authorization header.
10. Flask API with JSON Schema Validation
Validating JSON data with a schema using marshmallow.
This example shows how to validate input data against a schema using marshmallow.
These snippets cover a range of common functionalities when building RESTful APIs with Flask, such as handling different HTTP methods, query parameters, authentication, error handling, and validation.
Last updated