Creating a REST API Server with Swagger
This article will go over how to utilize Swagger to easily define a REST API Server. Swagger is a tool that allows you to define an API in the Open API specification model, and has a few different tools for further developing APIs once your specification is defined.
Swagger has a tool called the swagger-code-generator which allows you to generate Server or Client code for the API specification that you defined. By using this tool developers can save time by not having to manually set up the structure of the API involving the different web frameworks. You simply define your API Specification in the Swagger file then you can generate a REST API Server and Client!
Creating the Swagger Specification
Navigate to https://app.swaggerhub.com/home, create an account, and click “+ Create New” → “Create New API”.
This will allow you to start writing your specification in Swagger’s editor. Below is a sample swagger file you can copy into the editor, or if you would like to read more on defining Swagger specifications check out https://swagger.io/specification/.
description: "Swagger specification for MLB player compare"
title: "Base API"
name: "Apache 2.0"
summary: "Base Path Request"
description: "Get base path"
description: "Find out more about Swagger"
Generating the Server Codebase
Once you have your specification defined, look for the download button and hover to “Server” and click “Spring”. This will generate a Java Server codebase using the Spring framework which is a framework for creating standalone REST APIs. (More info on Spring) You could also generate framework code for other languages like Python and Scala, but for this tutorial we will be using Java’s Spring framework.
Next import your generated Server codebase into IntelliJ or any editor of your choice.
The generated server code is going to be set up to handle incoming request’s with the endpoints specified in your swagger file, but the responses to the requests will still need to be implemented. In the Java Spring framework, under src/main/java/io.swagger/api/ there is an APIController class with an unimplemented method. This method will be where you can configure the response for your API requests.
Starting your Server
To run your generated server, for the Java Spring framework, run the following commands.
java -jar target/swagger-spring-1.0.0.jar
This will compile and run the generated server on localhost:8080. I added this to a bash script to easily run my server while developing.
Implementing your API
Swagger code generator make it really easy to generate Server or client code to save you the time spent setting up the foundation of your API. The only steps necessary after generating your API is to implement the responses!