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
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 w3wiki!'}
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.
Integration with Swagger
The Swagger configuration has been expanded to include a title and set the UI version to 3 for a more modern look.
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 w3wiki!!'}
}
}
}
}
}
}
})
def get(self):
"""
This is an example endpoint which returns a simple message.
"""
return {'message': 'Welcome w3wiki!!'}
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
andPOST
. - 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.
- This class handles two HTTP methods:
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 w3wiki!!'}
}
}
}
}
}
}
})
def get(self):
"""
This is an example endpoint which returns a simple message.
"""
return {'message': 'Welcome w3wiki!!'}
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.
Implement a Python REST API with Flask & Flasgger
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.