- Prerequisites
- Setup
- Creating the Flask API
- Running the API
- Testing the API
- Extending the API
- Conclusion
Before you begin, ensure you have the following installed:
- Python 3.6 or higher: You can download it from python.org.
- pip: Python's package installer (comes with Python).
- Virtual Environment (optional but recommended): To manage dependencies.
-
Create a Project Directory
mkdir flask_api cd flask_api -
Set Up a Virtual Environment
It's good practice to use a virtual environment to manage dependencies.
python3 -m venv venv
Activate the virtual environment:
-
On Windows:
venv\Scripts\activate
-
On macOS and Linux:
source venv/bin/activate
-
-
Install Flask
pip install Flask
Here's a simple project structure:
flask_api/
│
├── app/
│ ├── __init__.py
│ ├── routes.py
│ └── models.py
│
├── venv/
│
├── requirements.txt
└── run.py
Create the __init__.py file inside the app directory:
# app/__init__.py
from flask import Flask
from flask import jsonify
def create_app():
app = Flask(__name__)
# Import and register blueprints
from .routes import main as main_blueprint
app.register_blueprint(main_blueprint)
# Error handling
@app.errorhandler(404)
def not_found(error):
return jsonify({'error': 'Not found'}), 404
@app.errorhandler(500)
def internal_error(error):
return jsonify({'error': 'Internal server error'}), 500
return appCreate the routes.py file inside the app directory:
# app/routes.py
from flask import Blueprint, request, jsonify
main = Blueprint('main', __name__)
# In-memory data store
items = []
@main.route('/', methods=['GET'])
def home():
return jsonify({'message': 'Welcome to the Flask API!'})
@main.route('/items', methods=['GET'])
def get_items():
return jsonify({'items': items})
@main.route('/items', methods=['POST'])
def add_item():
data = request.get_json()
if not data or 'name' not in data:
return jsonify({'error': 'Bad Request', 'message': 'Name is required'}), 400
item = {
'id': len(items) + 1,
'name': data['name']
}
items.append(item)
return jsonify({'item': item}), 201
@main.route('/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
item = next((item for item in items if item['id'] == item_id), None)
if item:
return jsonify({'item': item})
else:
return jsonify({'error': 'Item not found'}), 404
@main.route('/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
data = request.get_json()
if not data or 'name' not in data:
return jsonify({'error': 'Bad Request', 'message': 'Name is required'}), 400
item = next((item for item in items if item['id'] == item_id), None)
if item:
item['name'] = data['name']
return jsonify({'item': item})
else:
return jsonify({'error': 'Item not found'}), 404
@main.route('/items/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
global items
item = next((item for item in items if item['id'] == item_id), None)
if item:
items = [itm for itm in items if itm['id'] != item_id]
return jsonify({'message': 'Item deleted'})
else:
return jsonify({'error': 'Item not found'}), 404If you plan to use a database, you can define your models in models.py. For simplicity, we'll skip this in the basic setup.
This file will serve as the entry point to run the Flask application.
# run.py
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)It's helpful to have a requirements.txt file for dependencies.
pip freeze > requirements.txtThe requirements.txt should include:
Flask==2.3.2
(Note: The exact version may vary.)
-
Ensure the Virtual Environment is Activated
# On Windows venv\Scripts\activate # On macOS and Linux source venv/bin/activate
-
Run the Application
python run.py
You should see output similar to:
* Serving Flask app 'run' * Debug mode: on WARNING: This is a development server. Do not use it in a production deployment. * Running on http://127.0.0.1:5000 * Restarting with statThe API is now running at
http://127.0.0.1:5000.
You can test the API using tools like Postman, cURL, or even your web browser for GET requests.
- Endpoint:
GET / - Description: Returns a welcome message.
Example using cURL:
curl http://127.0.0.1:5000/Response:
{
"message": "Welcome to the Flask API!"
}- Endpoint:
GET /items - Description: Retrieves all items.
Example:
curl http://127.0.0.1:5000/itemsResponse:
{
"items": []
}- Endpoint:
POST /items - Description: Adds a new item.
- Payload: JSON object with a
namefield.
Example:
curl -X POST http://127.0.0.1:5000/items \
-H "Content-Type: application/json" \
-d '{"name": "Sample Item"}'Response:
{
"item": {
"id": 1,
"name": "Sample Item"
}
}- Endpoint:
GET /items/<id> - Description: Retrieves a single item by ID.
Example:
curl http://127.0.0.1:5000/items/1Response:
{
"item": {
"id": 1,
"name": "Sample Item"
}
}- Endpoint:
PUT /items/<id> - Description: Updates an existing item's name.
- Payload: JSON object with a
namefield.
Example:
curl -X PUT http://127.0.0.1:5000/items/1 \
-H "Content-Type: application/json" \
-d '{"name": "Updated Item"}'Response:
{
"item": {
"id": 1,
"name": "Updated Item"
}
}- Endpoint:
DELETE /items/<id> - Description: Deletes an item by ID.
Example:
curl -X DELETE http://127.0.0.1:5000/items/1Response:
{
"message": "Item deleted"
}