Flask Swagger Integration
Introduction
When developing RESTful APIs with Flask, providing clear and interactive documentation is essential for other developers who will consume your API. Swagger (now known as OpenAPI) is a powerful tool for documenting and visualizing your API endpoints. In this tutorial, you'll learn how to integrate Swagger with your Flask application to create interactive, user-friendly API documentation.
Swagger allows you to:
- Document your API endpoints in a standardized format
- Test API endpoints directly from a web interface
- Generate client SDKs automatically
- Make your APIs more accessible to others
Prerequisites
Before getting started, make sure you have:
- Basic knowledge of Flask and RESTful API concepts
- Python 3.6 or later installed
- A simple Flask application to work with
Setting Up Flask-Swagger
The most common way to integrate Swagger with Flask is using the flask-swagger-ui
package, which provides a Flask blueprint for the Swagger UI and a method for generating Swagger specifications.
Step 1: Install Required Packages
First, let's install the necessary packages:
pip install flask flask-restful flask-swagger-ui apispec marshmallow
Step 2: Create a Basic Flask Application
Let's start with a simple Flask API:
from flask import Flask, jsonify, request
app = Flask(__name__)
# Sample data
books = [
{"id": 1, "title": "Flask Web Development", "author": "Miguel Grinberg"},
{"id": 2, "title": "Python Crash Course", "author": "Eric Matthes"}
]
@app.route('/api/books', methods=['GET'])
def get_books():
return jsonify(books)
@app.route('/api/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
book = next((book for book in books if book['id'] == book_id), None)
if book:
return jsonify(book)
return jsonify({"error": "Book not found"}), 404
@app.route('/api/books', methods=['POST'])
def add_book():
if not request.json or 'title' not in request.json:
return jsonify({"error": "Invalid data"}), 400
book = {
'id': books[-1]['id'] + 1 if books else 1,
'title': request.json['title'],
'author': request.json.get('author', '')
}
books.append(book)
return jsonify(book), 201
if __name__ == '__main__':
app.run(debug=True)
Integrating Swagger UI with Your Flask Application
Now, let's integrate Swagger UI with our Flask application.
Step 3: Create a Swagger Configuration
We'll create a function to generate the Swagger documentation:
from flask_swagger_ui import get_swaggerui_blueprint
# Define the Swagger blueprint
SWAGGER_URL = '/api/docs' # URL for exposing Swagger UI (without trailing '/')
API_URL = '/static/swagger.json' # Our API url (can be a local file or url)
# Call factory function to create our blueprint
swaggerui_blueprint = get_swaggerui_blueprint(
SWAGGER_URL,
API_URL,
config={ # Swagger UI config overrides
'app_name': "Flask Book API"
}
)
# Register blueprint at URL
app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)
Step 4: Create a Swagger Specification File
Now we need to create a Swagger specification file that describes our API. Create a static
folder in your project root and add a file called swagger.json
:
import os
from flask import Flask, jsonify, request, send_from_directory
from flask_swagger_ui import get_swaggerui_blueprint
app = Flask(__name__)
# Create a route for serving the swagger.json file
@app.route('/static/swagger.json')
def swagger_json():
with open('static/swagger.json', 'r') as f:
return jsonify(json.load(f))
Now, create a static
folder and add a file named swagger.json
with the following content:
{
"swagger": "2.0",
"info": {
"title": "Flask Book API",
"description": "API for managing books",
"version": "1.0.0"
},
"basePath": "/api",
"schemes": [
"http"
],
"paths": {
"/books": {
"get": {
"summary": "Returns all books",
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "Successful operation",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Book"
}
}
}
}
},
"post": {
"summary": "Add a new book",
"produces": [
"application/json"
],
"parameters": [
{
"name": "book",
"in": "body",
"description": "Book object",
"required": true,
"schema": {
"$ref": "#/definitions/Book"
}
}
],
"responses": {
"201": {
"description": "Book created",
"schema": {
"$ref": "#/definitions/Book"
}
},
"400": {
"description": "Invalid input"
}
}
}
},
"/books/{bookId}": {
"get": {
"summary": "Find book by ID",
"produces": [
"application/json"
],
"parameters": [
{
"name": "bookId",
"in": "path",
"description": "ID of book to return",
"required": true,
"type": "integer"
}
],
"responses": {
"200": {
"description": "Successful operation",
"schema": {
"$ref": "#/definitions/Book"
}
},
"404": {
"description": "Book not found"
}
}
}
}
},
"definitions": {
"Book": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"title": {
"type": "string"
},
"author": {
"type": "string"
}
}
}
}
}