Quiz 2
Registry Synced

REST APIs with Flask

712 words
4 min read

Reading compass

Now · 🎯 Learning Objectives

REST APIs with Flask

🎯 Learning Objectives

  • Design RESTful API endpoints
  • Return JSON responses from Flask
  • Parse JSON request data
  • Use appropriate HTTP methods and status codes
  • Test APIs with curl and Postman

1. What is REST?

REST (Representational State Transfer) is an architectural style for APIs. Key principles:
  • Resources identified by URLs (e.g., /api/users/42)
  • HTTP methods = actions (GET=read, POST=create, PUT=update, DELETE=remove)
  • Stateless: each request contains all needed information
  • JSON is the standard data format

2. JSON APIs in Flask

python
from flask import Flask, jsonify, request
app = Flask(__name__)
# Sample data
books = [
    {'id': 1, 'title': '1984', 'author': 'George Orwell'},
    {'id': 2, 'title': 'To Kill a Mockingbird', 'author': 'Harper Lee'}
]
# GET all books
@app.route('/api/books', methods=['GET'])
def get_books():
    return jsonify(books)  # Automatically sets Content-Type: application/json
# GET single 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 new book
@app.route('/api/books', methods=['POST'])
def create_book():
    if not request.is_json:
        return jsonify({'error': 'Request must be JSON'}), 400
    data = request.get_json()
    required_fields = ['title', 'author']
    for field in required_fields:
        if field not in data:
            return jsonify({'error': f'Missing field: {field}'}), 400
    book = {
        'id': len(books) + 1,
        'title': data['title'],
        'author': data['author']
    }
    books.append(book)
    return jsonify(book), 201  # 201 Created
# PUT update book
@app.route('/api/books/<int:book_id>', methods=['PUT'])
def update_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
    data = request.get_json()
    book['title'] = data.get('title', book['title'])
    book['author'] = data.get('author', book['author'])
    return jsonify(book)
# DELETE 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 '', 204  # 204 No Content

3. Testing the API

bash
# GET all books
curl http://localhost:5000/api/books
# GET single book
curl http://localhost:5000/api/books/1
# POST new book
curl -X POST http://localhost:5000/api/books \
  -H "Content-Type: application/json" \
  -d '{"title":"Brave New World","author":"Aldous Huxley"}'
# PUT update
curl -X PUT http://localhost:5000/api/books/1 \
  -H "Content-Type: application/json" \
  -d '{"title":"Nineteen Eighty-Four"}'
# DELETE
curl -X DELETE http://localhost:5000/api/books/1

4. API Design Conventions

MethodEndpointActionStatus
GET/api/booksList all books200
GET/api/books/{id}Get one book200 / 404
POST/api/booksCreate a book201 / 400
PUT/api/books/{id}Update a book200 / 404
DELETE/api/books/{id}Delete a book204 / 404

5. Practice Questions

Q1: What does jsonify() do?
Answer: Converts Python data (dict, list) to JSON and returns a Flask Response with Content-Type: application/json. It also handles serialization of non-standard types (datetime, Decimal) properly. Q2: How do you read JSON from a request?
Answer: request.get_json() parses the request body as JSON and returns a Python dict. Check request.is_json first to ensure Content-Type is correct. Q3: What HTTP status code should a successful POST return?
Answer: 201 (Created), indicating a new resource was created. Optionally include the created resource in the response body and a Location header with the resource URL. Q4: What's the difference between PUT and POST?
Answer: POST creates a new resource (non-idempotent). PUT updates/replaces an existing resource (idempotent). POST to /api/books creates; PUT to /api/books/42 updates book 42. Q5: How do you handle a missing resource?
Answer: Return a 404 response with an error message:
python
return jsonify({'error': 'Book not found'}), 404
Q6: What does status 204 mean?
Answer: 204 No Content — the request succeeded but there's no response body. Commonly used for DELETE operations. Q7: How do you test a POST API with curl?
Answer:
bash
curl -X POST http://localhost:5000/api/books \
  -H "Content-Type: application/json" \
  -d '{"title":"Dune","author":"Frank Herbert"}'
Q8: What does request.is_json check?
Answer: It checks whether the request's Content-Type header is application/json. Returns False for form data or other content types.

📐 Key Concepts

MethodPurposeStatus Codes
GETRetrieve resource(s)200 OK
POSTCreate resource201 Created
PUTUpdate/replace resource200 OK
DELETEDelete resource204 No Content
ErrorBad request / Not found400 / 404

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.