
{{ $('Map tags to IDs').item.json.title }}
How to Build a Simple REST API with Flask
Flask is a popular micro web framework for Python that makes it easy to build web applications quickly. In this tutorial, you will learn how to create a simple REST API using Flask.
Prerequisites
- Basic knowledge of Python programming.
- Flask installed on your system (or the ability to install it).
1. Setting Up Your Environment
It is a good practice to create a virtual environment for your project. Navigate to your desired project folder in the terminal and run:
python3 -m venv venv
source venv/bin/activate
This creates a virtual environment and activates it. Once activated, you can install Flask.
2. Installing Flask
Install Flask using pip:
pip install Flask
3. Creating a Simple Flask Application
Create a new file named app.py
:
touch app.py
Open app.py
in your favorite text editor and add the following code:
from flask import Flask, jsonify, request
app = Flask(__name__)
# Sample data
items = [
{'id': 1, 'name': 'Item One'},
{'id': 2, 'name': 'Item Two'}
]
@app.route('/items', methods=['GET'])
def get_items():
return jsonify(items)
@app.route('/items', methods=['POST'])
def add_item():
new_item = request.get_json()
items.append(new_item)
return jsonify(new_item), 201
if __name__ == '__main__':
app.run(debug=True)
4. Running the Flask Application
To run your Flask application, execute the following command in the terminal:
python app.py
You should see output indicating that the server is running, usually on http://127.0.0.1:5000
.
5. Testing Your API
To test your API endpoints, you can use tools like curl
or Postman.
Testing the GET Request:
curl http://127.0.0.1:5000/items
This should return a JSON array of items.
Testing the POST Request:
curl -X POST -H "Content-Type: application/json" -d '{"id": 3, "name": "Item Three"}' http://127.0.0.1:5000/items
This command sends a new item to the API. You should receive the new item in the response.
6. Conclusion
Congratulations! You have created a simple REST API using Flask. This API allows you to retrieve and add items dynamically. Flask provides a robust framework for building APIs and web applications, and you can continue to enhance your application by adding features like error handling, authentication, and more.