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.
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.
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.
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