Build a mock REST API with Swagger UI using OPEN API Specification and Docker.
Nuvolar Works S.L
In this article, we are going to build a mock API using OpenAPI specification (OAS) and a Swagger UI in order to expose the API through a user interface directly. The entire implementation will be carried out using OpenAPI specification and a bit of docker, so no programming language is needed in order to have your API fully operational.
Docker & Compose:
VsCode (Optional but recommended):
- Some VSCode extensions
Some knowledge about REST APIs.
Please find our example repository with a completely functional implementation below. You can use it as a guide during the tutorial:
What is OpenAPI?
Imagine a software project that involves different teams (Front end, Backend, Devops). Usually, these projects start in parallel and all parties depend on the work of the rest of the teams. For example, a Single Page Application that needs to make queries to an API in order to get information from different users.
Firstly, all the system requirements must be defined properly, such as the different functionalities, the information across different systems, and so on. To meet all the expectations, the Backend Team will develop an API in order to interact with the storage systems and provide the necessary information to the Front end. At the same time, the Front end team will develop the User Interface and all of the user interactions.
To optimize development time, the Front End needs to know the API to which it will consult the information, what type of data and responses it will obtain, among other things. But what if the API development takes longer than Front End development itself?
That’s where the OpenAPI specification comes into play. An OpenAPI file allows you to fully describe your API, including:
- Available endpoints (/users) and operations on each endpoint (GET /users, POST /users).
- Operation parameters; Input and output for each operation.
- Authentication methods.
Basically, all of the information that third party systems need to interact with an API and thus start the integration phase, even if the backend development is not complete.
This is not only useful for Front End teams, but also for Backend developers as it will serve as a guide for the development of the final API.
What is Swagger?
Swagger is a set of open-source tools built around the OpenAPI Specification that can help you design, build, document, and consume REST APIs.
In this tutorial, we will focus only on Swagger UI, an interactive API documentation that helps users interact directly with APIs through the browser and retrieve mock data for development purposes.
- Build an OpenAPI specification file in order to define the API and its structure.
- Build the mock server using the OpenAPI specification file.
- Expose the OpenAPI specification through Swagger UI and connect it directly to the mock server in order to fetch already defined mock data.
- Build a compose file in order to orchestrate all the services and enable the project setup in a few steps.
1.Build an OpenAPI File API
Firstly, we need to develop our first API using OpenAPI specification. To do so, we can use an online editor, such as Swagger Editor by Swagger https://swagger.io/tools/swaggerhub/. This tool allows you to design, describe, and document your API in an online open-source environment.
As an alternative, we can use other options such as our IDE. In this case, VScode provides support to OpenAPI files, allowing us to preview the content and the rendering of the file through the IDE.
In this tutorial, we’ll use VSCode so that we’ll be able to split our OpenAPI specification file into different files and organize our API better.
Remember, the goal of this tutorial is not to go into how OpenAPI files are created in detail (although we will do a recap), but to understand how to integrate them with Swagger and create a mock server with them.
Now let’s create our first OpenAPI file!
First, open VSCode and create a new host folder. We are going to place all related files inside of this folder. Once created, we need to create a new json file. You can call it anything you want, but for simplicity, we’ll call it swagger.json. This file will contain all the OpenAPI specifications.
To work more efficiently, we’ll create different files to split the specification code. This will help to organize our API in blocks rather than having one single large file. The structure that we need will look like this:
As we can see in the previous image, the swagger.json file will orchestrate the entire OpenAPI specification. However, the rest of the files are also part of the documentation? and will contain code related to their own title. All components defined outside swagger.json can be accessed by it using references. You can learn more about how OpenAPI specification files are organized here: https://swagger.io/specification/
Let’s dive in a bit more with the different files. It is recommended to analyze the different files downloaded from the repository while reading this section in order to obtain a better understanding of the solution. In this example, we decided to implement a small API to consult Aircrafts and Airports (let’s assume that our company is related to the aviation industry :P)
This is the main file where the API configuration is defined andthe different paths and routes that the API will contain are displayed. Typically, all OpenAPI specification files can be declared in one single file. However, in this case we are using a different approach.
Let’s analyze the different labels:
- Openapi: Indicates the version of the used specification
- Info: Contains some meta information about the title, contact, and so on.
- Servers: Indicates the servers that will provide the information to the swagger requests. (In this case, the mock server that we’ll build with the same file).
- Tags: Name and description of the API resources.
- Paths: All the paths and resources are defined here. All the resources with its verbs, parameters and responses should be defined here. You can take a look at the implementation in the repository, but for this tutorial, a basic example is provided.
The OpenAPI specification file could also be created using different Swagger editors or in a single file.The way the Swagger.json file is built is up to you.
This file contains the different schemas that will be used in our API. All the objects and their types are defined here. Once defined, these schemas are used in the schema label under content label for each resource response. Schema Example:
- Responses & Responses_examples
This file contains the responses for the different endpoints. Each response should contain at least one schema in order to provide the schema documentation for each resource when requested through the Swagger UI. It is highly recommended to provide at least one example (response_examples.json) to provide the mock server with real responses.
All the parameters used in our API should be defined here. The name, location, description, schema, and other attributes should be defined for every parameter in order to be usable in our Swagger documentation.
2. Build the services (With docker compose)
In order to deploy our API, a compose file will be created. Compose is a tool used to define and run multi-container Docker applications. More information about compose is available here: https://docs.docker.com/compose/
This compose file will contain different services that will be in charge of carrying out different tasks:
- Validate and build a valid/final OpenAPI specification file built in the previous section. As references and multiple files are being used, a unique OpenAPI file must be created, gathering all the necessary information. This file must follow the requirements provided by OpenAPI specification (more on VSCode and OpenAPI). To do so, a docker service will be created in order to validate and build the final file that will be used to deploy the Mock server and the Swagger UI.
- Run and expose the Mock Server using the OpenAPI file generated in the step n. 1.
- Run and expose the Swagger UI using the OpenAPI file generated in the step n. 1.
In order to achieve all of the steps, our compose file will use different images pulled from the dockerhub created by 3rd parties.
- Swagger CLI: https://hub.docker.com/r/jeanberu/swagger-cli. This allows you to validate Swagger files or bundle them into a combined file.
- Open Api Mocker: https://github.com/jormaechea/open-api-mocker An API mocker based on the OpenAPI 3.0 specification.
- Swagger UI: https://hub.docker.com/r/swaggerapi/swagger-ui Swagger visualizator tool.
Let’s build a compose file that contains the different services. You can find this version in the provided repository.
The entire file is provided below with comments in-line in order to explain in detail the functionality of each service.
This docker-compose file must be located in the same folder as the rest of the documents.
3. Deploy the solution
Once we have our OpenAPI specification file completed and all of the necessary services declared, it is time to run the services.
- Open a terminal
- cd into the directory that contains all the files, e.g:
- $cd your_folder_containing_all_files
- Execute the following command in order to run the compose file:
- Docker-compose up (add -d if you want to run it in detached mode)
After running the commands, you’ll see that all of the services have started.
As shown, the swagger_build label has created the schema.json file properly. Then, the mock server and the Swagger UI were built around that file, exposing the mock server to the port 8000 of localhost and the Swagger UI at port 80 or localhost. (Notice that the message says the mock server is on port 5000, but that only applies inside docker’s network).
Open your browser and navigate to localhost:80/swagger, or just localhost/swagger, to check if the Swagger UI is working properly. You should see something like this:
Now you can make requests to the different endpoints and get real answers provided in the OpenAPI specification file, following all the requirements that you defined for your API.
Remember that you can use parameters, consult the schema of the responses and much more, allowing the frontenders to integrate development easily and without having the real API in production.
Notice that the Swagger UI is getting the data directly from the mock server (at localhost:8000). You can do regular HTTP requests directly to the mock server using services such as Postman, or by simply integrating the FE solution to get real information.
Here’s an example of a regular request to airports endpoint:
- Request: http://localhost:8080/airports
And that’s it! Every time a change is made to the specification, the compose file needs to be reloaded, stopping the service and repeating step 3.
Now you can define your APIs as well as offer and consult them without developing the final API! This will save a lot of time for both you and your teammates and increase the productivity of your team significantly!