Building a Swagger-Enabled RESTful API with Flask

Mohammed Farmaan
featurepreneur
2 min readJan 3, 2024

--

Introduction:

Developing RESTful APIs is a crucial aspect of modern web development, enabling seamless communication between frontend and backend systems. Flask, a lightweight Python web framework, provides an excellent foundation for building APIs. In this article, we’ll explore how to create a Flask API with Swagger documentation, enhancing the API development process. We’ll use Python, Flask, Marshmallow, APISpec, and Swagger UI to achieve this.

Tools and Libraries:

  1. Python:
  • Python serves as the programming language for developing our Flask API. Ensure you have Python installed on your machine.

2. Flask:

  • Flask is a lightweight web framework for Python, known for its simplicity and flexibility. Install Flask using the following command:
pip install Flask

3. Marshmallow:

  • Marshmallow is a library for object serialization and deserialization. It is useful for converting complex data types into Python objects. Install Marshmallow using:
pip install marshmallow

4. APISpec:

  • APISpec is a library for building API specifications. It allows us to define our API’s structure and generate Swagger documentation. Install APISpec using:
pip install apispec

5. Swagger UI:

  • Swagger UI is a user-friendly interface that visualizes and interacts with the API’s documentation. We’ll integrate it with our Flask API to provide a convenient way to explore and test the endpoints.

Setting Up the Flask API:

  1. Create a Flask App:
  • Start by creating a basic Flask application. Save the following code in a file named app.py:
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api/hello', methods=['GET'])
def hello():
return jsonify(message='Hello, Flask API!')

2. Define API Specification with APISpec and Marshmallow:

  • Define your API specification using Marshmallow for object serialization and APISpec for generating the Swagger documentation. Add the following code to your app.py file:
from flask_apispec import FlaskApiSpec
from marshmallow import Schema, fields

class HelloSchema(Schema):
message = fields.Str()

docs = FlaskApiSpec(app)

3. onfigure Flask to Use APISpec:

  • Configure Flask to use APISpec by adding the following lines to your app.py file:
app.config.update({
'APISPEC_SPEC': APISpec(
title='Flask API with Swagger',
version='v1',
plugins=['apispec.ext.marshmallow'],
),
'APISPEC_SWAGGER_URL': '/swagger/',
})

4. Document the Hello Endpoint:

  • Document the /api/hello endpoint using the defined schema. Add the following code:
@app.route('/api/hello', methods=['GET'])
@docs.doc(params={'message': {'description': 'A welcome message.'}})
@docs.response(code=200, description='Success', schema=HelloSchema)
def hello():
"""A simple endpoint that returns a welcome message."""
return jsonify(message='Hello, Flask API!')

5. un the Flask App:

  • Run your Flask app using the following command:
python app.py

Visit http://localhost:5000/swagger/ in your web browser to explore the Swagger documentation for your API.

Conclusion:

In this article, we covered the steps to create a Flask API with Swagger documentation. Leveraging Python, Flask, Marshmallow, APISpec, and Swagger UI, we’ve built a foundation for developing and documenting RESTful APIs efficiently.

You can expand upon this example by adding more endpoints, request validation, and customizing the Swagger UI appearance. Flask’s simplicity, combined with powerful libraries, makes it an excellent choice for API development. Happy coding!

--

--