from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/url", defaults={'param': None}, methods=["GET", "POST"])
@app.route("/url/<param>", methods=["GET", "POST"])
def url_route(param):
"""
Handle both GET and POST requests for the /url and /url/<param> endpoints.
- When accessed as /url, 'param' will be None.
- When accessed as /url/<param>, 'param' will contain the given value.
On a GET request, return a JSON response indicating the param state.
On a POST request, echo back any JSON data sent by the client.
"""
if request.method == "GET":
response = {
"message": "GET request received",
"param": param if param is not None else "No parameter provided"
}
return jsonify(response), 200
if request.method == "POST":
# Assume incoming data is JSON. If not, handle exceptions as needed.
data = request.get_json(silent=True) or {}
response = {
"message": "POST request received",
"param": param if param is not None else "No parameter provided",
"data_received": data
}
return jsonify(response), 201
if __name__ == "__main__":
app.run(debug=True)Flask Route Configuration with Optional Parameter Handling
Related Posts
More content you might like
Getting Started with Axios in JavaScript
const apiClient = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 1000,
headers: { 'X-Custom-Header': 'foobar' }
});
apiClient.get('/posts/1')
.then(response => {
console.log('Post:', response.data);
});- We create an Axios instance with a base URL and custom configuration.
- The instance can be reused for multiple requests, simplifying your code.
REST API Cheatsheet: Comprehensive Guide with Examples
REST (Representational State Transfer) is an architectural style for designing networked applications. It relies on a stateless, client-server communication protocol, usually HTTP. RESTful APIs are widely used due to their simplicity and scalability. This comprehensive cheatsheet covers essential REST API principles and operations, complete with examples presented in HTML tables for easy reference.
This REST API cheatsheet provides a comprehensive overview of the most commonly used REST API concepts, complete with examples to help you quickly find the information you need. Whether you're building or consuming APIs, this guide serves as a quick reference to help you work more efficiently with REST APIs.
Building a RESTful API with Go and Gorilla Mux
Create a new file named models.go to define the data structure for a book:
package main
type Book struct {
ID string `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
Year string `json:"year"`
}Creating a Simple REST API with Flask
Run the application:
python app.pyDiscussion 0
Please sign in to join the discussion.
No comments yet. Be the first to share your thoughts!