Neural Sync Active
REST APIs with Flask
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
pythonfrom 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
| Method | Endpoint | Action | Status |
|---|---|---|---|
| GET | /api/books | List all books | 200 |
| GET | /api/books/{id} | Get one book | 200 / 404 |
| POST | /api/books | Create a book | 201 / 400 |
| PUT | /api/books/{id} | Update a book | 200 / 404 |
| DELETE | /api/books/{id} | Delete a book | 204 / 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. Checkrequest.is_jsonfirst 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/bookscreates; PUT to/api/books/42updates book 42. Q5: How do you handle a missing resource?Answer: Return a 404 response with an error message:pythonreturn jsonify({'error': 'Book not found'}), 404Q6: 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:bashcurl -X POST http://localhost:5000/api/books \ -H "Content-Type: application/json" \ -d '{"title":"Dune","author":"Frank Herbert"}'Q8: What doesrequest.is_jsoncheck?Answer: It checks whether the request's Content-Type header isapplication/json. Returns False for form data or other content types.
📐 Key Concepts
| Method | Purpose | Status Codes |
|---|---|---|
| GET | Retrieve resource(s) | 200 OK |
| POST | Create resource | 201 Created |
| PUT | Update/replace resource | 200 OK |
| DELETE | Delete resource | 204 No Content |
| Error | Bad request / Not found | 400 / 404 |
🔗 Cross-References
- Next: Frontend-Backend Integration Join Discord Previous5.1 Sessions & CookiesNext7.1 Frontend-Backend Integration