Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Go
3.
What is an Open API?
4.
Gin Web Framework
5.
Swagger
6.
Generating Swagger Specification and Swagger UI
6.1.
Step 1: Create folders.
6.2.
Step 2: Initializing.
6.3.
Step 3: Pull the library.
6.4.
Step 4: Creation of a new central file
6.5.
Step 5: Run the app.
6.6.
Step 6: Updation
6.7.
Step 7: Pull libraries
6.8.
Step 8: Generate
6.9.
Step 9: Adding SwaggerUI.
6.10.
Step 10: Rerun
6.11.
Step 11: Call the newly added route.
6.12.
Step 12: Run the link.
7.
Frequently Asked Question  
7.1.
Does Go have a web framework?
7.2.
What is the Gin Engine in Golang?
7.3.
Is gin a good framework?
7.4.
Is Swagger a framework?
7.5.
What is the difference between API and Swagger?
8.
Conclusion
Last Updated: Mar 27, 2024

Gin - REST API and Test with Swagger (OpenAPI)

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

The programming language Go was created at Google by Robert, Rob, and Ken Thompson. It is statically typed and compiled. In this blog, we will learn more about the Gin REST API and test it using Swagger (OpenAPI).

Gin - REST API and Test with Swagger (OpenAPI)

Go

Go(Golang) has structural typing, garbage collection, memory safety, and concurrency in the CSP fashion. It is syntactically identical to C. As a result of its previous domain name, golang.org, it is frequently called Go, even though Go is its actual name.

Go

There are many implementations: 

  • WebAssembly and Google's "gc" compiler toolchain are self-hosted and targets many OS systems.
  • Using the libgo library, gofrontend is a frontend for various compilers. 
  • The GCC and LLVM are gccgo; the combination for LLVM is gollvm. 
  • GopherJS, an unofficial source-to-source compiler, compiles. When developing front-end websites, use JavaScript.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is an Open API?

An application programming interface (API) made publicly accessible to software developers is known as an open API or public API. Open APIs are available freely online and enable a network-accessible service to provide users with global access.

The OpenAPI Specification was formerly referred to as the Swagger Specification. It is a specification for an interface definition language that is machine-readable and used to describe, produce, consume, and visualize RESTful web services. It was once a component of the Swagger framework but split off into its project in 2016 and is now managed by the Linux Foundation's OpenAPI Initiative. Swagger and other tools may produce code, documentation, and test cases from interface files.

Gin Web Framework

Gin is a Golang-based web framework. Although it has a Martini-like API, it outperforms Martini by up to 40 times. Among the most popular Go frameworks is Gin. It is easy to use.

Martini is a robust Golang package that makes it simple to create modular web apps and services. Application Programming Interfaces (APIs) link developers and exchange helpful information and advancement. 

Gin Web Framework

They enable businesses to make their information and capabilities available to the general public for utilization. 

  • This data may subsequently be included in the apps we create.
  • It is optional to construct an application from scratch, for example, if you intend to assist consumers in locating popular eateries in their neighborhood. 
  • The Yelp API may be included in your program. However, developers will require explicit standards or followable documentation before sharing their API data. Here's where Swagger comes into play.

Swagger

Among the most popular tools for programmers to describe REST APIs is Swagger. Businesses like Google, Microsoft, and Netflix use Swagger. This essay will discuss the outstanding features of Swagger and the reasons why we suggest them.

Swagger

Specification

  • In software engineering, writing a specification requires excellent attention to detail. 
  • Whatever the case, it's essential if we want other people to utilize our API. 
  • It makes it simpler for others to integrate without using APIs. 
  • It will be simpler for others to incorporate the documentation into their systems the more influential it is. 
  • To address this issue, we should adhere to the OpenAPI Specification, previously called the Swagger Specification, which is the industry standard for creating API documentation. 
  • The global standard for creating RESTful interfaces is the OpenAPI Specification, previously called the Swagger Specification. 
  • The OAS allows developers to create a technology-neutral API interface as the foundation for their API creation and consumption.

Generating Swagger Specification and Swagger UI

Prerequisite

It would be best to have Go version ≥ 1.14 on your operating system.

Step 1: Create folders.

Development-related folders will be created. The application can be called ginnew.

$ mkdir ginnew
$ mkdir docs
$ mkdir docs/ginnew

Step 2: Initializing.

Initialize the “go” mod for the go vendor system.

$ go mod init

Step 3: Pull the library.

Pull the gin library.

$ go get -u github.com/gin-gonic/gin

Step 4: Creation of a new central file

In the ginnew folder, create a new file called “main.go” and paste the code below

package main
import (
  "log"
  "net/http"
  "github.com/gin-gonic/gin"
)
func main() {
  // Gin instance
  r := gin.New()
  // Routes
  r.GET("/", HealthCheck)
  // Start server
  if err := r.Run(":3000"); err != nil {
     log.Fatal(err)
  }
}
func HealthCheck(c *gin.Context) {
  res := map[string]interface{}{
     "data": "Server is up and running",
  }
  c.JSON(http.StatusOK, res)
}

Step 5: Run the app.

$ go run ginnew/main.go

An output like the one below will be displayed.
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] GET / --> main.HealthCheck (1 handlers)
[GIN-debug] Listening and serving HTTP on: 3000

This shows that port 3000 on the server is open and operational.

Step 6: Updation

Update the file "main.go" by adding declarative comments. These comments will be used later to generate Swagger specifications automatically.

package main
import (
  "log"
  "net/http"
  "github.com/gin-gonic/gin"
)
// @title Gin Swagger Example API
// @version 1.0
// @description This is an example of a Web server
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:3000
// @BasePath /
// @schemes http
func main() {
  // Gin instance
  r := gin.New()
 
  // Routes
  r.GET("/", HealthCheck)
  // Start server
  if err := r.Run(":3000"); err != nil {
     log.Fatal(err)
  }
}
// HealthCheck godoc
// @Summary Show the status of server.
// @Description get the status of server.
// @Tags root
// @Accept */*
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Router / [get]
func HealthCheck(c *gin.Context) {
  res := map[string]interface{}{
     "data": "Server is up and running",
  }
  c.JSON(http.StatusOK, res)
}

Step 7: Pull libraries

Pull the swagger libraries by making use of the commands below.

$ go get -v github.com/swaggo/swag/cmd/swag
$ go get -v github.com/swaggo/gin-swagger
$ go get -v github.com/swaggo/files

Step 8: Generate

The Swagger Specification needs to be generated.

$ swag init -g ginnew/main.go --output docs/ginnew

If the operation is successful, you will have 3 new files inside the folder docs/ginnew. 

These files are:

  • docs.go => Requires to generate SwaggerUI.
  • swagger.json => The Swagger Specification in json file format.
  • swagger.yaml => The Swagger Specification in yaml file format.

Step 9: Adding SwaggerUI.

Update main.go to add SwaggerUI.

package main
import (
  "log"
  "net/http"
  "github.com/gin-gonic/gin"
  _ "github.com/username/go-swag-sample/docs/ginnew"
  swaggerFiles "github.com/swaggo/files"
  ginSwagger "github.com/swaggo/gin-swagger"
)
// @title Gin Swagger Example API
// @version 2.0
// @description This is a sample server server.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:3000
// @BasePath /
// @schemes http
func main() {
  // Gin instance
  r := gin.New()
  // Routes
  r.GET("/", HealthCheck)
  url := ginSwagger.URL("http://localhost:3000/swagger/doc.json") // The URL pointing to API definition
  r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, url))
  // Start server
  if err := r.Run(":3000"); err != nil {
     log.Fatal(err)
  }
}
// HealthCheck godoc
// @Summary Show the status of the server.
// @Description get the status of server.
// @Tags root
// @Accept */*
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Router / [get]
func HealthCheck(c *gin.Context) {
  res := map[string]interface{}{
     "data": "Server is up and running",
  }
  c.JSON(http.StatusOK, res)
}

Step 10: Rerun

Now you may rerun the application.

$ go run ginnew/main.go

Step 11: Call the newly added route.

$ curl localhost:3000/swagger/doc.json
// 20210415135919
// http://localhost:3000/swagger/doc.json
{
 "schemes": [
   "http"
 ],
 "swagger": "2.0",
 "info": {
   "description": "This is a sample server server.",
   "title": "Gin Swagger Example API",
   "termsOfService": "http://swagger.io/terms/",
   "contact": {
     "name": "API Support",
     "url": "http://www.swagger.io/support",
     "email": "support@swagger.io"
   },
   "license": {
     "name": "Apache 2. 0",
     "url": "http://www.apache.org/licenses/LICENSE-2.0.html"
   },
   "version": "2.0"
 },
 "host": "localhost:3000",
 "basePath": "/",
 "paths": {
   "/": {
     "get": {
       "description": "get the status of server.",
       "consumes": [
         "*/*"
       ],
       "produces": [
         "application/json"
       ],
       "tags": [
         "root"
       ],
       "summary": "Show the status of server.",
       "responses": {
         "200": {
           "description": "OK",
           "schema": {
             "type": "object",
             "additionalProperties": true
           }
         }
       }
     }
   }
 }
}

Step 12: Run the link.

Open the SwaggerUI in the browser by clicking the URL below.

http://localhost:3000/swagger/index.html

Following the 12 steps above, we have created a simple Go web server using the Gin framework and generated the Swagger specification and SwaggerUI. 

Frequently Asked Question  

Does Go have a web framework?

Application programming interfaces (APIs) and online services are quickly created using Golang web frameworks. Frameworks are not required while developing tiny applications, but they are required for software meant for production.

What is the Gin Engine in Golang?

Gin is a Go-based, high-performance HTTP web framework. Routing and middleware are included as standard features and functions. By doing so, boilerplate code is reduced, productivity is increased, and the creation of microservices is made simpler.

Is gin a good framework?

Gin takes pride in being a Go framework that is incredibly quick. This is undoubtedly the case, and Gin excels at nearly every standard. Echo is not a sluggish framework but lacks the features Gin receives from HttpRouter.

Is Swagger a framework?

The most popular framework for creating APIs with a standard language is Swagger. However, a few substitute frameworks have become more well-known, such as RAML, APIBlueprint, and Summation.

What is the difference between API and Swagger?

Swagger and OpenAPI once had the same meaning. Although the phrases OpenAPI and Swagger now have different meanings (the former refers to a RESTful API architecture, while the latter refers to a collection of SmartBear tools), this blog will use both interchangeably.

Conclusion

This blog discusses the programming language Go. We will also learn more about the Gin REST API and Test using Swagger (OpenAPI). If you think this blog has helped you enhance your knowledge of the above question or want to learn more, check out our articles. Visit our website to read more such blogs. 

  1. Introduction to Swagger Documentation Format
  2. Main and Init Functions in Golang
  3. Gin - Setting up a JSON Web Token (JWT)

 

For placement preparations, you must look at the problemsinterview experiences, and interview bundles. Enroll in our courses and refer to the mock tests and problems available; look at the Problem Sheets interview experiences, and interview bundle for placement preparations. You can also book an interview session with us.  

Consider our paid courses, however, to give your career a competitive advantage!

Happy Coding!

Live masterclass