Concepts
- Routing: The process of mapping URLs to specific functions in your Flask application. These functions are called “views” and handle user requests for those URLs.
- URL Endpoints: Specific URLs within your application that trigger the corresponding view functions.
- HTTP Methods: Flask supports various HTTP methods (GET, POST, PUT, DELETE) for different actions on a resource.
Creating Routes:
Import Flask:
from flask import Flask
Create a Flask Application Instance:
app = Flask(__name__)
Define a Route:
@app.route('/path/to/your/resource') # Define the URL endpoint
def your_view_function():
# This function will be executed when the user accesses the URL
return 'Hello, World!'
The @app.route()
decorator associates the URL (/path/to/your/resource
) with the your_view_function
function.
The function can return any data you want to display in the user’s browser (usually a string or a rendered template).
Dynamic Routes:
You can use placeholders in your routes to capture dynamic parts of the URL:
@app.route('/users/<username>')
def get_user(username):
# The username will be accessible as a variable in the function
return f'Hello, {username}!'
In this example, <username>
is a placeholder that captures any value provided in the URL segment after “/users/”.
The captured value is accessible as a variable username
within the get_user
function.
from flask import Flask
app = Flask(__name__)
@app.route('/users/<username>')
def get_user(username):
return f'Hello, {username}!'
if __name__ == '__main__':
app.run(debug=True)
Result: user vinh.nguyen
HTTP Methods:
By default, routes only respond to GET requests. You can specify different HTTP methods with the methods
argument in the decorator:
@app.route('/products', methods=['GET', 'POST'])
def products():
# This function can handle both GET (retrieving products) and POST (creating a new product) requests
...
Example of Post method
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/process_data', methods=['POST'])
def process_data():
data = request.get_json()
# Validate and process the data (replace with your logic)
if 'name' in data and 'age' in data:
name = data['name']
age = data['age']
return f'Hello, {name}! You are {age} years old.', 201
else:
return 'Invalid data format. Please provide "name" and "age" in JSON format.', 400
if __name__ == '__main__':
app.run(debug=True)
Explanation:
- Imports: We import
Flask
for creating the application,request
for accessing request data, andjsonify
for returning JSON responses. - App Creation: We create a Flask application instance named
app
. - Route Definition:
- We define a route
/process_data
using the@app.route
decorator. - We explicitly specify
methods=['POST']
to indicate this route only handles POST requests.
- We define a route
- View Function:
- The
process_data
function handles requests to this route.
- The
- Accessing Data:
- We use
request.get_json()
to access the data sent in the request body. This assumes the data is formatted in JSON. - Important: Implement proper error handling and validation for
request.get_json()
in production environments to avoid potential issues.
- We use
- Data Processing:
- We perform basic data validation to check if required keys (“name” and “age”) are present in the JSON data.
- Replace this with your actual data processing and validation logic.
- Returning Responses:
- If data is valid, we return a formatted string message with a status code of 201 (Created).
- If data is invalid, we return an error message with a status code of 400 (Bad Request).
jsonify
helps convert the response data to JSON format.
- Running the Application:
- We use the
if __name__ == '__main__':
block to ensure the code within only runs when the script is executed directly (not imported as a module). - We call
app.run(debug=True)
to start the Flask development server in debug mode.
- We use the
Testing the Example:
- Save the code as a Python file (e.g.,
post_example.py
). - Run the application using
flask run
in your terminal. - Use tools like Postman or curl to send a POST request to
http://127.0.0.1:5000/process_data
with a JSON body containing “name” and “age” keys. For example, using curl:
curl -X POST http://127.0.0.1:5000/process_data -H "Content-Type: application/json" -d '{"name": "Corgi", "age": 8}'
- 4. The response should be a JSON message indicating successful data processing or an error message if the data is invalid.
Result
The default interactive shell is now zsh.
To update your account to use zsh, please run `chsh -s /bin/zsh`.
For more details, please visit https://support.apple.com/kb/HT208050.
(base) [nqvinhtong@Vince-MacBook-Pro python]$curl -X POST http://127.0.0.1:5000/process_data -H "Content-Type: application/json" -d '{"name": "Corgi", "age": 8}'
Hello, Corgi! You are 8 years old.