Implement a Python REST API with Flask & Flasgger
Last Updated :
17 May, 2024
Building a RESTful API in Python can be straightforward with Flask, a lightweight and flexible web framework. To add comprehensive documentation and interactive features to the API, Flasgger is a powerful tool that integrates Swagger UI with Flask. This article guides you through the process of implementing a REST API using Flask and Flasgger.
What is Flasgger?
Flasgger is a Python library that facilitates the creation and management of Swagger (OpenAPI) documentation for Flask web applications. Swagger is a framework for describing APIs using a common language that allows both humans and computers to understand the capabilities of a web service without access to the source code.
Key features of Flasgger include:
- Easy Integration: Flasgger integrates seamlessly with Flask applications, allowing developers to add API documentation with minimal configuration.
- Automatic Documentation: It can automatically generate API documentation from Flask routes and view functions, using docstrings and other metadata.
- Swagger UI: Flasgger provides a built-in Swagger UI, an interactive web interface that allows users to explore and test API endpoints.
- Customization: Developers can customize the documentation by defining the schema, adding parameters, responses, and examples directly in the docstrings or using YAML files.
- Validation: It supports request validation against the defined schema to ensure that incoming requests meet the expected format and constraints.
First API Development with Swagger
Here's a step-by-step guide to creating a Code-First API development with Swagger in Python using the Flask web framework:
Setting up Environment
- Make sure you have Python pre-installed in your system.
- Install these required libraries like Flask and Flask-RESTful as shown below in a command prompt.
pip install flask
pip install Flask-RESTful
pip install flasgger
Create a Flask APP
Create a new Python file named app.py , for example
Python
from flask import Flask
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
class Welcome(Resource):
def get(self):
return {'message': 'Welcome to GeeksforGeeks!'}
api.add_resource(Welcome, '/')
if __name__ == '__main__':
app.run(debug=True)
Output:
Run this file as shown in the code snippet below:
python app.py
Then the app will be running on local host http://127.0.0.1:5000. Open the localhost http://127.0.0.1:5000 and the output will be as shown in the below figure.
Flask Api without SwaggerIntegration with Swagger
The Swagger configuration has been expanded to include a title and set the UI version to 3 for a more modern look.
Python
from flask import Flask, request
from flask_restful import Api, Resource
from flasgger import Swagger, swag_from
app = Flask(__name__)
api = Api(app)
# Configuring Swagger
app.config['SWAGGER'] = {
'title': 'My API',
'uiversion': 3
}
swagger = Swagger(app)
class Welcome(Resource):
@swag_from({
'responses': {
200: {
'description': 'A status code 200 means successful and returns a message.',
'content': {
'application/json': {
'examples': {
'example1': {
'summary': 'Successful response',
'value': {'message': 'Welcome GeeksforGeeks!!'}
}
}
}
}
}
}
})
def get(self):
"""
This is an example endpoint which returns a simple message.
"""
return {'message': 'Welcome GeeksforGeeks!!'}
api.add_resource(Welcome, '/')
if __name__ == '__main__':
app.run(debug=True)
Output
Creating one more API
A new class Items has been added, inheriting from Resource. This class handles the /items endpoint.
Items
Class:- This class handles two HTTP methods:
GET
and POST
. - The
get
method returns a list of items. - The
post
method adds a new item to the list. For simplicity, the item is returned in the response, and in a real application, it would typically be added to a database or another data store.
Python
from flask import Flask, request
from flask_restful import Api, Resource
from flasgger import Swagger, swag_from
app = Flask(__name__)
api = Api(app)
# Configuring Swagger
app.config['SWAGGER'] = {
'title': 'My API',
'uiversion': 3
}
swagger = Swagger(app)
class Welcome(Resource):
@swag_from({
'responses': {
200: {
'description': 'A status code 200 means successful and returns a message.',
'content': {
'application/json': {
'examples': {
'example1': {
'summary': 'Successful response',
'value': {'message': 'Welcome GeeksforGeeks!!'}
}
}
}
}
}
}
})
def get(self):
"""
This is an example endpoint which returns a simple message.
"""
return {'message': 'Welcome GeeksforGeeks!!'}
class Items(Resource):
@swag_from({
'responses': {
200: {
'description': 'A status code 200 means successful and returns a list of items.',
'content': {
'application/json': {
'examples': {
'example1': {
'summary': 'Successful response',
'value': {'items': ['Item 1', 'Item 2', 'Item 3']}
}
}
}
}
}
}
})
def get(self):
"""
This endpoint returns a list of items.
"""
items = ['Item 1', 'Item 2', 'Item 3']
return {'items': items}
api.add_resource(Welcome, '/')
api.add_resource(Items, '/items')
if __name__ == '__main__':
app.run(debug=True)
Run this file as shown in the code snippet below:
python app.py
- Then the app will be running on local host http://127.0.0.1:5000.
- Open the localhost http://127.0.0.1:5000/apidocs/
- Swagger UI will be opened (Flasgger).
- The GET Api call will be displayed , if there are no errors in the code and environment as shown in below output image.
Output:
Output will be displayed as shown in below image.
Similar Reads
Python | Build a REST API using Flask
Prerequisite: Introduction to Rest API REST stands for REpresentational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data. In this article, we will build a REST API in Python using the Fla
3 min read
Flask project - Create a Joke App with PyJokes
Flask is a micro web framework written in Python. It is classified as a micro-framework because it does not require particular tools or libraries. Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex app
2 min read
Top 10 Python REST API Frameworks in 2025
In a rapidly changing web development scene, REST APIs have emerged as the underlying functionality that allows for the development of scalable and efficient applications. Python is a simple and versatile language, much helped by a mature ecosystem of frameworks for building REST APIs. The right cho
10 min read
How to Implement Filtering, Sorting, and Pagination in Flask
Python-based Flask is a microweb framework. Due to the fact that it doesn't require any specific tools or libraries, it is categorized as a micro-framework. It lacks any components where pre-existing third-party libraries already provide common functionality, such as a database abstraction layer, fo
6 min read
How to write a simple Flask API for hello world?
Prerequisites: Introduction to REST API REST stands for Representational State Transfer and is an architectural style used in modern web development. It defines a set of rules/constraints for a web application to send and receive data. In this article, we are going to learn how to create a simple RE
3 min read
Implement ChatGPT in a Flask Application
You can build dynamic and interactive chat interfaces by integrating ChatGPT into a Flask application. This article's instructions can help you integrate ChatGPT into your Flask project and give users engaging chat experiences. Improve the user interface, try out new prompts, and look into new optio
3 min read
Create a Weather app using Flask | Python
Prerequisite : Flask installation Flask is a lightweight framework written in Python. It is lightweight because it does not require particular tools or libraries and allow rapid web development. today we will create a weather app using flask as a web framework. this weather web app will provide curr
2 min read
Python Flask Projects with Source Code (Beginners to Advanced)
Flask, a Python web application framework, was created by Armin Ronacher. Known for its lightweight and efficient nature, Flask is designed for quick starts and accommodates complex applications. It is based on the Werkzeug WSGI toolkit and Jinja2 template engine. In this article, weâve curated a li
4 min read
Responsive Chart with Bokeh, Flask and Python
In this post, we will use the Flask framework to create our web application in Python. The Bokeh library will be used to create interactive graphs and we will visualize this graph through a simple frontend HTML page. For this, we will first write the endpoints in Flask which will help us to create B
5 min read
Form Submission API with Swagger Editor and Python Flask
Creating user-friendly APIs is essential for seamless interaction between applications. Leveraging tools like Swagger Editor alongside Python Flask, developers can streamline the process of designing, documenting, and implementing APIs. In this guide, we'll explore how to craft a Form Submission API
3 min read