How to Build a REST API with Flask: A Step-by-Step Guide
Flask is a lightweight Python framework that makes building REST APIs fast and straightforward. In this tutorial, you’ll learn how to create a simple RESTful API with Flask, covering project setup, endpoint creation, request handling, and testing. By the end, you’ll have a functional API you can extend for your own projects.
Setting Up Flask
First, create a virtual environment and install Flask:
python -m venv venvsource venv/bin/activate(orvenv\Scripts\activateon Windows)pip install flask
Create a file named app.py and import Flask:
from flask import Flask, request, jsonify
app = Flask(__name__)
Defining Routes and Endpoints
Use Flask decorators to map HTTP methods to functions. For a simple CRUD API for a resource called “items”:
GET /items– return all itemsPOST /items– create a new itemGET /items/<id>– get a single itemPUT /items/<id>– update an itemDELETE /items/<id>– delete an item
Example route:
items = []
@app.route('/items', methods=['GET'])
def get_items():
return jsonify(items)
Handling Requests and Responses
Access request data with request.get_json() for POST/PUT. Return JSON using jsonify(). Include proper HTTP status codes:
@app.route('/items', methods=['POST'])
def create_item():
data = request.get_json()
new_item = {"id": len(items)+1, "name": data["name"]}
items.append(new_item)
return jsonify(new_item), 201
Testing Your API
Run the app with flask run. Test using curl or tools like Postman:
curl http://127.0.0.1:5000/itemscurl -X POST -H "Content-Type: application/json" -d '{"name":"Book"}' http://127.0.0.1:5000/items
Flask’s built-in server is fine for development. For production, use a WSGI server like Gunicorn.
Conclusion: Flask’s simplicity lets you build REST APIs quickly. Start with the basic structure above, then add authentication, database integration, and error handling as needed. Happy coding!