I want to set up a mock server for python-flask in seconds using swagger-codegen.

Introduction

Even though I'm not familiar with Web servers in my work We would like to introduce swagger-codegen to those who have been told to set up a web server for PoC (and in seconds). (It may not be possible to set up in seconds, but if you write the API specification in yaml, you can easily set up the server.)

About swagger-codegen

When swagger-codegen defines API specifications in YAML (or JSON), Create a mock server according to the API definition, In addition, you can create a browser UI screen where you can hit the API as shown below.

image.png

usage environment

Install JRE

If you do not have JRE, download and install it from the following.

Get swagger-codegen-cli.jar

Obtained from the maven repository.

This time, I used the following 2.4.15.

API specification defined in swagger.yaml

If you define the API specification, you can create a mock server according to the definition. Create a file like the one below.

swagger.yaml


swagger: "2.0"
info:
  description: "This is an API for pet stores."
  version: "1.0.0"
  title: "Petstore API"
  termsOfService: "http://swagger.io/terms/"
  contact:
    email: "[email protected]"
  license:
    name: "Apache 2.0"
    url: "http://www.apache.org/licenses/LICENSE-2.0.html"
paths:
  /pet/{petId}:
    get:
      summary: "Pet information API"
      description: "Returns information for the specified petId"
      parameters:
      - name: "petId"
        in: "path"
        description: "ID of the pet you want to get"
        required: true
        type: "integer"
        format: "int64"
      responses:
        200:
          description: "Response on success"
          schema:
            type: "object"
            properties:
              id:
                type: "integer"
                format: "int64"
              name:
                type: "string"
                example: "doggie"

Please refer to the following for the meaning of the description in swagger.yml.

Create a mock server

This time I want to use the familiar python, so I will create a mock server with pytoh-flask.

> java -jar {Downloaded jar file} generate -i swagger.yaml -l python-flask -o test-server

You can make Go, Node.js, Ruby on Rails, whatever by changing the -l option. See below for what else the -l option has.

Created folder structure

In the case of python-flask, you can create a mock server like this. Since a Dockerfile is also created, it is also possible to make it a Docker container.

> tree server
server
├── Dockerfile
├── README.md
├── git_push.sh
├── requirements.txt
├── setup.py
├── swagger_server
│   ├── __init__.py
│   ├── __main__.py
│   ├── controllers
│   │   ├── __init__.py
│   │   └── default_controller.py
│   ├── encoder.py
│   ├── models
│   │   ├── __init__.py
│   │   ├── base_model_.py
│   │   └── inline_response200.py
│   ├── swagger
│   │   └── swagger.yaml
│   ├── test
│   │   ├── __init__.py
│   │   └── test_default_controller.py
│   └── util.py
├── test-requirements.txt
└── tox.ini

In this, the actual processing is described in the pet_pet_id_get part of default_controller.py.

default_controller.py


import connexion
import six

from swagger_server.models.inline_response200 import InlineResponse200  # noqa: E501
from swagger_server import util


def pet_pet_id_get(petId):  # noqa: E501
    """Pet information API

Returns information for the specified petId# noqa: E501

    :param petId:ID of the pet you want to get
    :type petId: int

    :rtype: InlineResponse200
    """
    return 'do some magic!'

Try running it in a conda environment on Windows.

Install the required packages. Only pip requirements.txt is written in the environment created by swagger-codegen, In the conda environment, you can run it by installing the following.

> conda install connexion
> conda install swagger-ui-bundle

start up.

> cd test-server
> python -m swagger_server

If you access the following from a browser and see the screen, you can start it.

Thank you for your hard work!

Recommended Posts

I want to set up a mock server for python-flask in seconds using swagger-codegen.
Set up a local web server in 30 seconds using python 3's http.server
I want to print in a comprehension
Set up a mail server using Twisted
Set up a simple HTTPS server in Python 3
I want to create a window in Python
Set up a test SMTP server in Python.
Set up a UDP server in C language
How to set up a local development server
Set up a simple SMTP server in Python
I want to set a life cycle in the task definition of ECS
Python program is slow! I want to speed up! In such a case ...
I want to embed a variable in a Python string
I want to easily implement a timeout in python
How to set up a Python environment using pyenv
I want to transition with a button in flask
Set up a file server on Ubuntu 20.04 using Samba
I want to write in Python! (2) Let's write a test
I want to randomly sample a file in Python
I want to work with a robot in python.
Set up a free server on AWS in 30 minutes
I want to write in Python! (3) Utilize the mock
When you want to plt.save in a for statement
I want to save a file with "Do not compress images in file" set in OpenPyXL
Find a guideline for the number of processes / threads to set in the application server
[Python] I want to get a common set between numpy
I tried to make a stopwatch using tkinter in python
I want to make input () a nice complement in python
I want to create a Dockerfile for the time being.
How to set up a simple SMTP server that can be tested locally in Python
I want to set up a GUI development environment with Python or Golang on Mac
I want to create a pipfile and reflect it in docker
I get a can't set attribute when using @property in python
Set up a node to do MNIST on ROS using Tensorflow
[Hi Py (Part 1)] I want to make something for the time being, so first set a goal.
How to make a model for object detection using YOLO in 3 hours
(Matplotlib) I want to draw a graph with a size specified in pixels
Send mail with mailx to a dummy SMTP server set up with python.
I want to convert a table converted to PDF in Python back to CSV
I analyzed Airbnb data for those who want to stay in Amsterdam
I want to sort a list in the order of other lists
Try to set up a Vim test environment quite seriously (for Python)
I want to color a part of an Excel string in Python
A note I looked up to make a command line tool in Python
I want to make a web application using React and Python flask
I want to do a monkey patch only partially safely in Python
Set up a Samba server with Docker
How to set up SVM using Optuna
I want to build a Python environment
I want to embed Matplotlib in PySimpleGUI
I want to create a nice Python development environment for my new Mac
I want to create a priority queue that can be updated in Python (2.7)
If you want to display values using choices in a template in a Django model
[Django memo] I want to set the login user information in the form in advance
I want to add silence to the beginning of a wav file for 1 second
I want to see a list of WebDAV files in the Requests module
I searched for the skills needed to become a web engineer in Python
I want to do machine learning even without a server --Time Series Edition -
I set up TensowFlow and was addicted to it, so make a note
I want to make matplotlib a dark theme
Set up a simple HTTPS server with asyncio