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.

PrincipleMeaning
Client-ServerThe API and the consumer are separate programs
StatelessEach request carries all the info needed; no session state
Uniform InterfaceURLs identify resources; HTTP methods describe actions
Resource-BasedEverything 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'}), 200

HTTP Status Codes for APIs

CodeMeaningUse For
200 OKSuccessGET, PUT, PATCH, DELETE success
201 CreatedResource createdSuccessful POST
400 Bad RequestInvalid inputMissing or malformed data
401 UnauthorizedAuthentication requiredNo valid API key or token
403 ForbiddenAccess deniedAuthenticated but not permitted
404 Not FoundResource missingID doesn't exist
500 Server ErrorSomething brokeUnhandled 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/1

Summary

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.

Leave a Comment

Your email address will not be published. Required fields are marked *