Flask Swagger
Integrating Swagger with Flask allows you to automatically generate API documentation that describes the endpoints, request parameters, and responses of your Flask application. Swagger UI provides an interactive interface that helps developers visualize and interact with the API resources. Here’s a step-by-step tutorial on how to integrate Swagger with Flask using Flask-RESTPlus, a Flask extension that simplifies the creation of REST APIs with Swagger documentation.
Step-by-Step Tutorial for Flask-Swagger (Flask-RESTPlus)
1. Install Required Packages
First, install Flask-RESTPlus and Flask:
pip install Flask Flask-RESTPlus
2. Set Up Your Flask Application
Create a new directory for your project and set up the following files:
- app.py: Main entry point for your Flask application.
- config.py: Configuration settings for your Flask app (optional for this tutorial).
- resources.py: Define your API resources here.
3. Initialize Flask Application with Flask-RESTPlus
app.py:
from flask import Flask
from flask_restplus import Api, Resource, fields
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
api = Api(app,
version='1.0',
title='Todo API',
description='A simple Todo API',
)
if __name__ == '__main__':
app.run(debug=True)
4. Define Resources Using Flask-RESTPlus
resources.py:
from flask_restplus import Resource, fields
from app import api
# Define the namespace
ns = api.namespace('todos', description='Todo operations')
# Model for Todo item
todo_model = api.model('Todo', {
'id': fields.Integer(readOnly=True, description='The task unique identifier'),
'task': fields.String(required=True, description='The task details')
})
# Mock data
todos = [
{'id': 1, 'task': 'Do homework'},
{'id': 2, 'task': 'Read a book'},
]
@ns.route('/')
class TodoListResource(Resource):
@ns.doc('list_todos')
@ns.marshal_list_with(todo_model)
def get(self):
"""List all todos"""
return todos
@ns.doc('create_todo')
@ns.expect(todo_model)
@ns.marshal_with(todo_model, code=201)
def post(self):
"""Create a new todo"""
new_todo = api.payload
new_todo['id'] = len(todos) + 1
todos.append(new_todo)
return new_todo, 201
@ns.route('/<int:id>')
@ns.response(404, 'Todo not found')
@ns.param('id', 'The task identifier')
class TodoResource(Resource):
@ns.doc('get_todo')
@ns.marshal_with(todo_model)
def get(self, id):
"""Fetch a todo given its identifier"""
todo = next((todo for todo in todos if todo['id'] == id), None)
if todo:
return todo
api.abort(404, f"Todo {id} not found")
@ns.doc('update_todo')
@ns.expect(todo_model)
@ns.marshal_with(todo_model)
def put(self, id):
"""Update a todo given its identifier"""
todo = next((todo for todo in todos if todo['id'] == id), None)
if todo:
todo.update(api.payload)
return todo
api.abort(404, f"Todo {id} not found")
@ns.doc('delete_todo')
@ns.response(204, 'Todo deleted')
def delete(self, id):
"""Delete a todo given its identifier"""
global todos
todos = [todo for todo in todos if todo['id'] != id]
return '', 204
5. Run the Application
Start your Flask development server:
python app.py
Accessing Swagger UI
- Once your Flask application is running, access Swagger UI at
http://localhost:5000/swagger
. - You'll see the Swagger UI interface showing your API endpoints, request parameters, and responses based on the definitions provided in your
resources.py
.
Summary
In this tutorial, you’ve learned how to integrate Swagger with Flask using Flask-RESTPlus to automatically generate API documentation. Flask-RESTPlus simplifies the creation of REST APIs by providing abstractions for defining namespaces, models, and routes. Swagger UI provides an interactive interface for developers to explore and test the API endpoints easily. This setup not only enhances the development experience but also improves API documentation and communication across teams working on Flask-based projects.