Python flask restful example

Cora 123 Published: 11/15/2024

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 list

tasks = [

{"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.

Use OAuth 2.0: Implement OAuth 2.0 for authentication and authorization. This allows clients to access your API without sharing their credentials.

Python libraries like oauthlib and requests-oauthlib can help you implement OAuth 2.0.

Validate User Input: Validate all user input, including request headers, query parameters, and body data. Use a whitelist approach by only allowing specific fields and values.

In Python, you can use the jsonschema library to validate JSON requests.

Use a Secure Password Hashing Algorithm: Store passwords securely using a salted hashing algorithm like bcrypt or scrypt.

Python libraries like bcrypt and passlib provide implementations of these algorithms.

Implement Rate Limiting: Throttle requests from clients to prevent brute-force attacks, scraping, or other malicious activities.

You can implement rate limiting using a Python library like ratelimit.

Log and Monitor Requests: Log all API requests, including errors and exceptions, to detect and respond to security incidents.

In Python, you can use libraries like logbook and logging for logging and monitoring requests.

Use Content Security Policy (CSP): Define which sources of content are allowed to be executed within your application.

Python libraries like csp provide implementations of CSP.

Keep Your Dependencies Up-to-Date: Regularly update your Python dependencies, including Flask or Django, and any third-party libraries used in your API.

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.

Conduct Regular Security Audits and Penetration Testing: Periodically audit your API's security and perform penetration testing to identify vulnerabilities and improve overall security.

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.