Here is a simple yet complete template for a RESTful API using Flask and the Flask-RESTful extension, which is a common and effective way to build APIs.
This example creates a simple “To-Do List” API where you can get, create, update, and delete tasks.
First, you’ll need to install Flask and Flask-RESTful.
Bash
pip install flask flask-restful
app.py)Create a file named app.py and paste the following code into it. The comments explain what each part does.
Python
# Import necessary libraries
from flask import Flask, request
from flask_restful import Resource, Api, reqparse, abort
# Initialize the Flask application
app = Flask(__name__)
# Initialize the Flask-RESTful API
api = Api(app)
# A simple in-memory database (a dictionary) to store our tasks
TASKS = {
'task1': {'task': 'build a RESTful API'},
'task2': {'task': 'learn more about Flask'},
'task3': {'task': 'profit!'},
}
# --- Helper Functions ---
def abort_if_task_doesnt_exist(task_id):
"""Function to check if a task ID exists in our database."""
if task_id not in TASKS:
abort(404, message=f"Task {task_id} doesn't exist")
# --- Argument Parser ---
# This helps validate and parse incoming request data for POST and PUT
parser = reqparse.RequestParser()
parser.add_argument('task', type=str, required=True, help='Task description cannot be blank!')
# --- Resource for a single task ---
# This resource will handle GET, DELETE, and PUT requests for a specific task.
class Task(Resource):
def get(self, task_id):
"""Retrieve a single task."""
abort_if_task_doesnt_exist(task_id)
return TASKS[task_id]
def delete(self, task_id):
"""Delete a task."""
abort_if_task_doesnt_exist(task_id)
del TASKS[task_id]
# Return an empty response with a 204 No Content status code
return '', 204
def put(self, task_id):
"""Update a task."""
abort_if_task_doesnt_exist(task_id)
args = parser.parse_args()
task = {'task': args['task']}
TASKS[task_id] = task
return task, 200
# --- Resource for the list of all tasks ---
# This resource will handle GET requests for all tasks and POST to create new tasks.
class TaskList(Resource):
def get(self):
"""Retrieve the list of all tasks."""
return TASKS
def post(self):
"""Create a new task."""
args = parser.parse_args()
# Create a new task ID (simple incrementing logic)
task_id = f'task{int(max(TASKS.keys()).lstrip("task")) + 1}'
TASKS[task_id] = {'task': args['task']}
# Return the newly created task with a 201 Created status code
return TASKS[task_id], 201
# --- API Resource Routing ---
# This is where we define the URLs for our resources.
# The '/tasks' endpoint will be handled by the TaskList resource.
api.add_resource(TaskList, '/tasks')
# The '/tasks/<task_id>' endpoint will be handled by the Task resource.
# The <task_id> part is a variable that will be passed to the methods (get, put, delete).
api.add_resource(Task, '/tasks/<string:task_id>')
# --- Main execution block ---
# This runs the Flask development server.
# debug=True provides helpful error messages and auto-reloads the server on code changes.
if __name__ == '__main__':
app.run(debug=True)
app.py.python app.pyYou should see output indicating that the server is running, typically on http://127.0.0.1:5000/.
You can use a tool like curl in your terminal, or a GUI application like Postman, to send requests to your new API. Here are the curl commands:
Bash
curl http://127.0.0.1:5000/tasks
Expected Output:
JSON
{"task1": {"task": "build a RESTful API"}, "task2": {"task": "learn more about Flask"}, "task3": {"task": "profit!"}}
Bash
curl http://127.0.0.1:5000/tasks/task2
Expected Output:
JSON
{"task": "learn more about Flask"}
curl http://127.0.0.1:5000/tasks/task3 -X DELETE
Bash
(No JSON output, but the command succeeds. You can run the GET all command again to verify it’s gone.)
Bash
curl http://127.0.0.1:5000/tasks -X POST -H "Content-Type: application/json" -d '{"task": "go to the store"}'
Expected Output:
JSON
{"task": "go to the store"}
(This will be created as task4.)
Bash
curl http://127.0.0.1:5000/tasks/task1 -X PUT -H "Content-Type: application/json" -d '{"task": "build an AWESOME RESTful API"}'
Expected Output:
JSON
{"task": "build an AWESOME RESTful API"}
This template provides a solid foundation. You can expand it by connecting it to a real database (like PostgreSQL with SQLAlchemy), adding authentication, and structuring your project into multiple files for better organization.