Flask series building Swagger UI style web API

Explain

  • Operating system: Windows 10
  • Python version: 3.7x
  • Virtual Environment Manager: virtualenv
  • Code editor: VS Code

Experiment

Environment initialization

# Create project directory
mkdir helloworld
cd helloworld

# Create a virtual environment
python -m virtualenv venv
# Activate virtual environment
venv\Scripts\activate

# Install environment package
pip install flask flask-restplus

# Start VS Code
code .

Experimental example

Hello World

from flask import Flask
from flask_restplus import Api, Resource

app = Flask(__name__)
api_app = Api(app=app,
              version='1.0',
              title='Main',
              description='Main APIs')
name_space = api_app.namespace(name='helloworld',
                               description='The helloworld APIs EndPoint.')


@name_space.route('/')
class HelloWorld(Resource):
    def get(self):
        return {
            'status': 'you get a request.'
        }

    def post(self):
        return {
            'status': 'you post a request.'
        }


if __name__ == "__main__":
    app.run(debug=True)

The operation effect of the program is shown in the following figure:

At this point, we can request a get and a post request interface created above through the Swagger UI or curl.

Parameter passing

For parameter passing, we only need to add parameter configuration to our interface definition, as shown in the following example code:

@name_space.route('/<int:id>')
class HelloWorld(Resource):
    @api_app.doc(responses={
        200: 'ok',
        400: 'not found',
        500: 'something is error'
    }, params={
        'id': 'the task identifier'
    })
    def get(self, id):
        return {
            'status': 'you get a request.',
            'id': id
        }

    def post(self, id):
        return {
            'status': 'you post a request.'
        }

The operation structure is as follows:

Entity delivery

In the above two example codes, we know how to define WebAPI and parameter passing. Let's extract a Todo example on the official homepage to show how to use it completely:

from flask import Flask
from flask_restplus import Api, Resource, fields

app = Flask(__name__)
api = Api(app, version='1.0', title='TodoMVC API',
          description='A simple TodoMVC API',
          )

# Configure API space nodes
ns = api.namespace('todos', description='TODO operations')

# Configure the interface data model (this data model is oriented to external services, which should be distinguished from the data model in the database in the actual project)
todo = api.model('Todo', {
    'id': fields.Integer(readOnly=True, description='The task unique identifier'),
    'task': fields.String(required=True, description='The task details')
})

# Define interface entities
class TodoDAO(object):
    def __init__(self):
        self.counter = 0
        self.todos = []

    def get(self, id):
        for todo in self.todos:
            if todo['id'] == id:
                return todo
        api.abort(404, "Todo {} doesn't exist".format(id))

    def create(self, data):
        todo = data
        todo['id'] = self.counter = self.counter + 1
        self.todos.append(todo)
        return todo

    def update(self, id, data):
        todo = self.get(id)
        todo.update(data)
        return todo

    def delete(self, id):
        todo = self.get(id)
        self.todos.remove(todo)

# Create seed data
DAO = TodoDAO()
DAO.create({'task': 'Build an API'})
DAO.create({'task': '?????'})
DAO.create({'task': 'profit!'})

# Define service interface
@ns.route('/')
class TodoList(Resource):
    '''Shows a list of all todos, and lets you POST to add new tasks'''
    @ns.doc('list_todos')
    @ns.marshal_list_with(todo)
    def get(self):
        '''List all tasks'''
        return DAO.todos

    @ns.doc('create_todo')
    @ns.expect(todo)
    @ns.marshal_with(todo, code=201)
    def post(self):
        '''Create a new task'''
        return DAO.create(api.payload), 201

# Define service interface
@ns.route('/<int:id>')
@ns.response(404, 'Todo not found')
@ns.param('id', 'The task identifier')
class Todo(Resource):
    '''Show a single todo item and lets you delete them'''
    @ns.doc('get_todo')
    @ns.marshal_with(todo)
    def get(self, id):
        '''Fetch a given resource'''
        return DAO.get(id)

    @ns.doc('delete_todo')
    @ns.response(204, 'Todo deleted')
    def delete(self, id):
        '''Delete a task given its identifier'''
        DAO.delete(id)
        return '', 204

    @ns.expect(todo)
    @ns.marshal_with(todo)
    def put(self, id):
        '''Update a task given its identifier'''
        return DAO.update(id, api.payload)


if __name__ == '__main__':
    app.run(debug=True)

The operation effect of the program is shown in the following figure:

summary

There are many web API packages based on flag to create Swagger UI style, such as

They all have their own advantages and disadvantages, but as far as my current usage is concerned, I prefer to build flash restplus, so I'll share them here.

At the end of the day, Amway's personal website: hippiezhou , the Bing wallpaper plate contains the daily Bing wallpaper, I hope you like it.

Project reference

Tags: Python Windows pip curl

Posted on Sun, 10 Nov 2019 15:36:40 -0500 by Spoiler