Python flask restful example
Python flask restful example
Here is a simple example of how to create a RESTful API with Flask in Python:
What's the goal?
We want to create an API that allows users to add, remove, and retrieve data from a list of "to-do" tasks.
The code:
First, let's install Flask:
pip install flask
Now, let's write the code for our RESTful API:
from flask import Flask, jsonify, request
app = Flask(name)
Sample data for our to-do listtasks = [
{"id": 1, "task": "Buy milk"},
{"id": 2, "task": "Walk the dog"},
...]
@app.route('/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
@app.route('/tasks/int:task_id', methods=['GET'])
def get_task(task_id):
for task in tasks:
if task['id'] == task_id:
return jsonify({'task': task})
return jsonify({'error': 'Task not found'})
@app.route('/tasks', methods=['POST'])
def add_task():
new_task = {'id': len(tasks) + 1, 'task': request.json['task']}
tasks.append(new_task)
return jsonify({'task': new_task}), 201
@app.route('/tasks/int:task_id', methods=['DELETE'])
def delete_task(task_id):
for task in tasks:
if task['id'] == task_id:
tasks.remove(task)
return jsonify({'message': 'Task deleted'})
return jsonify({'error': 'Task not found'})
if name == 'main':
app.run(debug=True)
Let me explain what each part of the code does:
@app.route('/tasks', methods=['GET'])
: This route returns a JSON response with all the tasks in our to-do list. @app.route('/tasks/<int:task_id>', methods=['GET'])
: This route returns a JSON response with a specific task based on its ID. If no matching task is found, it returns an error message. @app.route('/tasks', methods=['POST'])
: This route creates a new task and adds it to the list of tasks. It also returns a JSON response with the newly created task. @app.route('/tasks/<int:task_id>', methods=['DELETE'])
: This route deletes a specific task based on its ID. If no matching task is found, it returns an error message.
How does it work?
To test our API, we can use tools like Postman or cURL to send HTTP requests to the API endpoints. For example:
To get all tasks:GET http://localhost:5000/tasks
To get a specific task: GET http://localhost:5000/tasks/<task_id>
To add a new task: POST http://localhost:5000/tasks
with JSON body { "task": "New task" }
To delete a task: DELETE http://localhost:5000/tasks/<task_id>
This is just a simple example, but I hope it gives you an idea of how to create a RESTful API with Flask in Python!
How to secure REST API in Python?
Securing a REST API in Python involves implementing various security measures to protect it from unauthorized access, data breaches, and other threats. Here are some best practices to follow:
Use HTTPS: Enable HTTPS (Hypertext Transfer Protocol Secure) to encrypt communication between the client and server. This prevents eavesdropping, tampering, and man-in-the-middle attacks.In Python, you can use the ssl
module or a library like cryptography
to create an SSL/TLS certificate.
Python libraries like oauthlib
and requests-oauthlib
can help you implement OAuth 2.0.
In Python, you can use the jsonschema
library to validate JSON requests.
Python libraries like bcrypt
and passlib
provide implementations of these algorithms.
You can implement rate limiting using a Python library like ratelimit
.
In Python, you can use libraries like logbook
and logging
for logging and monitoring requests.
Python libraries like csp
provide implementations of CSP.
Older versions of dependencies can contain known vulnerabilities.
Implement Input Validation for File Uploads: Validate file uploads to prevent attacks like file inclusion vulnerability (FI) and file upload exploit.Python libraries like flask-werkzeug
provide implementations of input validation for file uploads.
In Python, you can use libraries like safety
and sqlmap
to conduct security audits and penetration testing.
By following these best practices, you can significantly enhance the security of your REST API in Python. Remember to always keep your dependencies up-to-date and be mindful of potential vulnerabilities.
Note: This response is written in English only, as per the initial request.