Projektstruktur
flask_api_project/
├── app.py
├── books.py
├── models.py
└── venv/
In-Memory Datenmodell (models.py)
# models.py
books = [
{ 'id': 1, 'title': 'Der Hobbit', 'author': 'J.R.R. Tolkien', 'year': 1937 },
{ 'id': 2, 'title': 'Harry Potter...', 'author': 'J.K. Rowling', 'year': 1997 },
{ 'id': 3, 'title': 'Die Verwandlung', 'author': 'Franz Kafka', 'year': 1915 }
]
next_id = len(books) + 1
# Funktionen: get_all_books(), get_book(), add_book(), update_book(), delete_book()
Flask-Routen – books.py
# Blueprint + Endpoints
@books_bp.route('/api/books', methods=['GET']) # Alle Bücher
@books_bp.route('/api/books/<int:id>', methods=['GET']) # Einzelnes Buch
@books_bp.route('/api/books', methods=['POST']) # Neues Buch
@books_bp.route('/api/books/<int:id>', methods=['PUT']) # Buch aktualisieren
@books_bp.route('/api/books/<int:id>', methods=['DELETE'])# Buch löschen
Hauptanwendung – app.py
from flask import Flask
from books import books_bp
app = Flask(__name__)
app.register_blueprint(books_bp)
@app.route('/api')
def info():
return {'name': 'Book API', 'version': '1.0'}
if __name__ == '__main__':
app.run(debug=True)
API testen (curl)
curl http://localhost:5000/api/bookscurl -X POST -H "Content-Type: application/json" -d '{"title":"1984","author":"G. Orwell"}' http://localhost:5000/api/books
Gelernt:
- CRUD mit Flask-Blueprints
- HTTP-Methoden & JSON-Antworten
- In-Memory Datenverwaltung
- Fehlerbehandlung mit Statuscodes
Zurück zum Blog