Flask REST API Basics
A REST API lets different programs communicate over HTTP. Instead of returning HTML pages, a REST API returns data — usually JSON — that other applications, mobile apps, or JavaScript frontends consume. Flask builds REST APIs with the same routing system used for web pages.
What REST Means
REST stands for Representational State Transfer. It is not a technology — it is a set of design principles for building web APIs.
| Principle | Meaning |
|---|---|
| Client-Server | The API and the consumer are separate programs |
| Stateless | Each request carries all the info needed; no session state |
| Uniform Interface | URLs identify resources; HTTP methods describe actions |
| Resource-Based | Everything is a resource: /users, /posts, /orders |
REST URL and Method Convention
Resource: /users GET /users → list all users POST /users → create a new user GET /users/42 → get user with ID 42 PUT /users/42 → replace user 42 completely PATCH /users/42 → update specific fields of user 42 DELETE /users/42 → delete user 42
A Simple Flask REST API
from flask import Flask, jsonify, request
app = Flask(__name__)
# In-memory data store for demonstration
books = [
{'id': 1, 'title': 'Flask Web Development', 'author': 'Miguel Grinberg'},
{'id': 2, 'title': 'Python Crash Course', 'author': 'Eric Matthes'},
]
# GET all books
@app.route('/api/books', methods=['GET'])
def get_books():
return jsonify(books)
# GET one book
@app.route('/api/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)
# POST — create a new book
@app.route('/api/books', methods=['POST'])
def create_book():
data = request.get_json()
if not data or 'title' not in data:
return jsonify({'error': 'Title is required'}), 400
new_book = {
'id': max(b['id'] for b in books) + 1,
'title': data['title'],
'author': data.get('author', 'Unknown')
}
books.append(new_book)
return jsonify(new_book), 201
# DELETE a book
@app.route('/api/books/<int:book_id>', methods=['DELETE'])
def delete_book(book_id):
global books
book = next((b for b in books if b['id'] == book_id), None)
if book is None:
return jsonify({'error': 'Book not found'}), 404
books = [b for b in books if b['id'] != book_id]
return jsonify({'message': 'Book deleted'}), 200HTTP Status Codes for APIs
| Code | Meaning | Use For |
|---|---|---|
| 200 OK | Success | GET, PUT, PATCH, DELETE success |
| 201 Created | Resource created | Successful POST |
| 400 Bad Request | Invalid input | Missing or malformed data |
| 401 Unauthorized | Authentication required | No valid API key or token |
| 403 Forbidden | Access denied | Authenticated but not permitted |
| 404 Not Found | Resource missing | ID doesn't exist |
| 500 Server Error | Something broke | Unhandled exception |
Testing Your API
Use curl from the terminal to test your endpoints during development:
# GET all books
curl http://127.0.0.1:5000/api/books
# POST a new book (with JSON body)
curl -X POST http://127.0.0.1:5000/api/books \
-H "Content-Type: application/json" \
-d '{"title": "Clean Code", "author": "Robert Martin"}'
# DELETE a book
curl -X DELETE http://127.0.0.1:5000/api/books/1Summary
A Flask REST API uses the same routing system as a regular Flask app, but returns JSON data instead of HTML. Use jsonify() to convert Python dictionaries and lists to JSON responses. Follow REST conventions: URLs name resources, HTTP methods describe actions, and status codes communicate the outcome. Test endpoints with curl or API tools like Postman during development.
