Flask Items API with Validation

easyPython

Lesson

Building REST APIs with Flask

REST APIs (Representational State Transfer) are a standard way to build web services that allow different applications to communicate over HTTP. Flask makes it easy to create REST APIs by mapping HTTP methods (GET, POST, PUT, DELETE) to specific URLs.

Core Concepts

Routes and HTTP Methods: In Flask, you define routes using decorators that specify both the URL path and the HTTP methods it accepts. GET requests typically retrieve data, while POST requests create new resources.

JSON Communication: REST APIs commonly use JSON for data exchange. Flask provides request.get_json() to parse incoming JSON data and jsonify() to convert Python dictionaries into JSON responses.

Status Codes: HTTP status codes communicate the result of an operation. 200 means success, 201 means "created successfully", 400 indicates client errors (like validation failures), and 500 indicates server errors.

Data Validation: Always validate incoming data before processing it. Check that required fields exist, data types are correct, and values meet your business rules. Return clear error messages when validation fails.

Request/Response Flow

When a client sends a request to your API, Flask routes it to the appropriate handler function. Your function processes the request (possibly validating data or querying a database), then returns a response. The response includes both data (usually JSON) and an HTTP status code.

For stateful operations like creating resources, you'll often need to maintain data in memory (using global variables for simple cases) or persist it to a database. Each new resource typically gets a unique identifier that clients can use for future operations.

Example
1from flask import Flask, request, jsonify 2 3app = Flask(__name__) 4users = [] # Simple in-memory storage 5 6@app.route('/users', methods=['GET']) 7def get_users(): 8 return jsonify({'users': users}) 9 10@app.route('/users', methods=['POST']) 11def create_user(): 12 data = request.get_json() 13 14 # Validation 15 if not data or 'email' not in data: 16 return jsonify({'error': 'Email is required'}), 400 17 18 # Create and store user 19 new_user = {'id': len(users) + 1, 'email': data['email']} 20 users.append(new_user) 21 22 return jsonify({'user': new_user}), 201
L4Global list serves as simple in-memory database
L6Route decorator specifies URL path and HTTP method
L11request.get_json() parses the incoming JSON request body
L19Return 201 status code for successful resource creation

Key Takeaways

  • •REST APIs use HTTP methods (GET, POST, etc.) to perform different operations on resources
  • •Always validate incoming data and return appropriate HTTP status codes
  • •Flask's jsonify() and request.get_json() handle JSON serialization and parsing automatically
Loading...