Building a REST API with Python and Flask
Learn how to build a REST API with Python and Flask from scratch. This guide covers routes, JSON responses, HTTP methods, and testing your API with practical examples.
Building a REST API with Python is one of the most useful skills a backend developer can have. APIs power everything from mobile apps to third-party integrations. Flask makes it surprisingly straightforward to build one. Let’s go from zero to a working API.
What Makes an API “RESTful”?
REST (Representational State Transfer) is a set of conventions for how web services communicate. A RESTful API uses HTTP methods to perform operations on resources:
- GET — read data
- POST — create data
- PUT/PATCH — update data
- DELETE — remove data
Each resource has its own URL (called an endpoint), like /users or /products/42.
Setting Up Your Flask API
Install Flask and create app.py:
from flask import Flask, jsonify, request
app = Flask(__name__)
# In-memory "database" for this example
books = [
{"id": 1, "title": "Python Crash Course", "author": "Eric Matthes"},
{"id": 2, "title": "Fluent Python", "author": "Luciano Ramalho"},
]
@app.route("/books", methods=["GET"])
def get_books():
return jsonify(books)
@app.route("/books/<int:book_id>", methods=["GET"])
def get_book(book_id):
book = next((b for b in books if b["id"] == book_id), None)
if book is None:
return jsonify({"error": "Book not found"}), 404
return jsonify(book)
@app.route("/books", methods=["POST"])
def create_book():
data = request.get_json()
new_book = {"id": len(books) + 1, "title": data["title"], "author": data["author"]}
books.append(new_book)
return jsonify(new_book), 201
if __name__ == "__main__":
app.run(debug=True)
jsonify() converts Python dictionaries to JSON responses. The 201 status code means “created” — returning the right status codes is part of good REST API design.
Testing Your REST API
You don’t need a frontend to test your API. Use curl in the terminal:
# Get all books
curl http://localhost:5000/books
# Create a new book
curl -X POST http://localhost:5000/books \
-H "Content-Type: application/json" \
-d '{"title": "Clean Code", "author": "Robert Martin"}'
Or install Postman for a graphical interface — it’s free and much easier for exploring APIs visually.
Conclusion
You now have a working REST API with Python and Flask — GET and POST endpoints, JSON responses, and proper status codes. From here, connect it to a real database like PostgreSQL, add authentication, and deploy it. Every web and mobile app you use relies on an API like this one.
Read next: Connecting Python to PostgreSQL with psycopg2
External resource: Flask — Quickstart
Related Articles
Docker for Backend Developers: A Practical Introduction
Learn how Docker works, why backend developers need it, and how to containerize your first Python or Go application in under 30 minutes.
Containerising a Backend Service: From Docker to Kubernetes
A practical walkthrough of containerising a Python backend service with Docker, deploying it to Kubernetes on ECS, and the production gaps that only show up once real traffic hits.
Environment Variables Explained: Keeping Secrets Out of Code
Learn what environment variables are and why every developer needs them. This guide covers how to use .env files, os.environ in Python, process.env in Node.js, and best practices.