SlideShare a Scribd company logo
www.bacancytechnology.com
Being a developer, you might understand
how important it is to document and
organize all the APIs, and you also know not
every developer likes this documentation
part. For that, we need some tools that can
be easily used to prepare API
documentation. Well, the very first tool that
strikes is Swagger.
What is
Swagger?
Swagger is a set of open-source tools for
writing REST-based APIs. It simplifies the
process of writing APIs by notches,
specifying the standards & providing the
tools required to write and organize
scalable APIs.
Why use
Swagger?
As mentioned before, when we have to
follow methodology, documentations are a
‘must.’ With swagger, we can create API
documentation by just adding comments in
code.


Now the question might strike Is Swagger
just for API documentation? No, it’s not.


With Swagger, we can generate clients for
any technologies like Node, AngularJS, PHP,
and many more. Thus, it is good for naming
conventions, maintaining best practices,
and common structure for our application.
Also, it does save coding time on the client
side.


Now, let’s see what we will do in this
tutorial.
Tutorial Goal:
Golang API
Documentation
using Go
Swagger.
In this tutorial, we will make a demo
application and prepare API documentation
using go-swagger. Watch the video below to
have a look at what we are going to build in
this tutorial.
Go Swagger
Example: How
to Create
Golang API
Documentation
Without further ado, let’s get started with
the coding part. Here are the step-by-step
instructions to create Golang API
documentation.


Create Project Directory
Use the below commands to create a project
directory.
mkdir goswagger
cd goswagger
go mod init goswagger
Install Swagger
download_url=$(curl -s
https://api.github.com/repos/go-
swagger/go-swagger/releases/latest | 
jq -r '.assets[] | select(.name |
contains("'"$(uname | tr '[:upper:]'
'[:lower:]')"'_amd64")) |
.browser_download_url')
curl -o /usr/local/bin/swagger -L'#'
"$download_url"
chmod +x /usr/local/bin/swagger
Downloading
Dependencies
Next, we will download the required
dependencies


For this demo, we will use:
Mux: Handling http requests and
routing


Command:


go get github.com/gorilla/mux
Swagger: Handling swagger doc


Command:


go get github.com/go-
openapi/runtime/middleware
MySQL: Handling MySQL queries


Commands:


github.com/go-sql-driver/mysql
go get github.com/jmoiron/sqlx
Import Database
company.sql from the Root
Directory


Create main.go in the root directory.
Establish database connection, routing for
APIs, and Swagger documentation.




r := mux.NewRouter()
dbsqlx := config.ConnectDBSqlx()
hsqlx :=
controllers.NewBaseHandlerSqlx(dbsqlx)
company :=
r.PathPrefix("/admin/company").Subrouter()
company.HandleFunc("/",
hsqlx.PostCompanySqlx).Methods("POST")
company.HandleFunc("/",
hsqlx.GetCompaniesSqlx).Methods("GET")
company.HandleFunc("/{id}",
hsqlx.EditCompany).Methods("PUT")
company.HandleFunc("/{id}",
hsqlx.DeleteCompany).Methods("DELETE")
Write Documentation using
Go Swagger
Now, let’s see how to document using
Swagger. It will consist of basic
configurations, models, and API routes.
Basic Configuration
// Comapany Api:
// version: 0.0.1
// title: Comapany Api
// Schemes: http, https
// Host: localhost:5000
// BasePath: /
// Produces:
// - application/json
//
// securityDefinitions:
// apiKey:
// type: apiKey
// in: header
// name: authorization
// swagger:meta
package controllers
For security definition, we can use the API
key, which can be verified for every API.


Models


Create models for requests and responses
for our APIs. Below are some examples of
structure with swagger comments. We can
add name, type, schema, required, and
description for every field.


type ReqAddCompany struct {
// Name of the company
// in: string
Name string
`json:"name"validate:"required,min=2,max=
100,alpha_space"`
// Status of the company
// in: int64
Status int64 `json:"status"
validate:"required"`
}
// swagger:parameters admin addCompany
type ReqCompanyBody struct {
// - name: body
// in: body
// description: name and status
// schema:
// type: object
// "$ref": "#/definitions/ReqAddCompany"
// required: true
Body ReqAddCompany `json:"body"`
}
// swagger:model Company
type Company struct {
// Id of the company
// in: int64
Id int64 `json:"id"`
// Name of the company
// in: string
Name string `json:"name"`
// Status of the company
// in: int64
Status int64 `json:"status"`
}
// swagger:model CommonError
type CommonError struct {
// Status of the error
// in: int64
Status int64 `json:"status"`
// Message of the error
// in: string
Message string `json:"message"`
}


API Routes


We can add swagger comments for every
route. In which we can specify request and
response models, route name, the request
method, description, and API key if
required.
// swagger:route GET /admin/company/
admin listCompany
// Get companies list
//
// security:
// - apiKey: []
// responses:
// 401: CommonError
// 200: GetCompanies
func (h *BaseHandlerSqlx)
GetCompaniesSqlx(w http.ResponseWriter,
r *http.Request) {
response := GetCompanies{}
companies :=
models.GetCompaniesSqlx(h.db)
response.Status = 1
response.Message = lang.Get("success")
response.Data = companies
w.Header().Set("content-type",
"application/json")
json.NewEncoder(w).Encode(response)
}
// swagger:route POST /admin/company/
admin addCompany
// Create a new company
//
// security:
// - apiKey: []
// responses:
// 401: CommonError
// 200: GetCompany
func (h *BaseHandlerSqlx)
PostCompanySqlx(w http.ResponseWriter, r
*http.Request) {
w.Header().Set("content-type",
"application/json")
response := GetCompany{}
decoder := json.NewDecoder(r.Body)
var reqcompany *models.ReqCompany
err := decoder.Decode(&reqcompany)
fmt.Println(err)
if err != nil {
json.NewEncoder(w).Encode(ErrHandler(la
ng.Get("invalid_requuest")))
return
}
company, errmessage :=
models.PostCompanySqlx(h.db,
reqcompany)
if errmessage != "" {
json.NewEncoder(w).Encode(ErrHandler(er
rmessage))
return
}
response.Status = 1
response.Message =
lang.Get("insert_success")
response.Data = company
json.NewEncoder(w).Encode(response)
}
// swagger:route PUT /admin/company/{id}
admin editCompany
// Edit a company
//
// consumes:
// - application/x-www-form-
urlencoded
// security:
// - apiKey: []
// responses:
// 401: CommonError
// 200: GetCompany
func (h *BaseHandlerSqlx) EditCompany(w
http.ResponseWriter, r *http.Request) {
r.ParseForm()
w.Header().Set("content-type",
"application/json")
vars := mux.Vars(r)
response := GetCompany{}
id, err := strconv.ParseInt(vars["id"], 10, 64)
if err != nil {
json.NewEncoder(w).Encode(ErrHandler(l
ang.Get("invalid_requuest")))
return
}
var reqcompany models.ReqCompany
reqcompany.Status, err =
strconv.ParseInt(r.FormValue("status"), 10,
64)
reqcompany.Name =
r.FormValue("name")
if err != nil {
json.NewEncoder(w).Encode(ErrHandler(l
ang.Get("invalid_requuest")))
return
}
company, errmessage :=
models.EditCompany(h.db, &reqcompany,
id)
if errmessage != "" {
json.NewEncoder(w).Encode(ErrHandler(er
rmessage))
return
}
response.Status = 1
response.Message =
lang.Get("update_success")
response.Data = company
json.NewEncoder(w).Encode(response)
}
// swagger:route DELETE
/admin/company/{id} admin
deleteCompany
// Delete company
//
// security:
// - apiKey: []
// responses:
// 401: CommonError
// 200: CommonSuccess
// Create handles Delete get company
func (h *BaseHandlerSqlx)
DeleteCompany(w http.ResponseWriter, r
*http.Request) {
vars := mux.Vars(r)
errmessage := models.DeleteCompany(h.db,
vars["id"])
if errmessage != "" {
json.NewEncoder(w).Encode(ErrHandler(er
rmessage))
return
}
successresponse := CommonSuccess{}
successresponse.Status = 1
successresponse.Message =
lang.Get("delete_success")
w.Header().Set("content-type",
"application/json")
json.NewEncoder(w).Encode(successrespon
se)
}


After done with api, we can generate
swagger yaml or JSON files from swagger
comments using the below command in the
root directory.


swagger generate spec -o ./swagger.yaml –
scan-models
It will generate a swagger.yaml file in the
root directory. We can also create a JSON
file the same way.


Using this file, we can add routes for
documentation in the main.go file.


// documentation for developers
opts :=
middleware.SwaggerUIOpts{SpecURL:
"/swagger.yaml"}
sh := middleware.SwaggerUI(opts, nil)
r.Handle("/docs", sh)
// documentation for share
// opts1 :=
middleware.RedocOpts{SpecURL:
"/swagger.yaml"}
// sh1 := middleware.Redoc(opts1, nil)
// r.Handle("/docs", sh1)
Once you are done with the steps,
documentation for developers will look
something like the below images.


Refer to the below documentation for Read-
Only APIs that you want to share with
external developers.
Go swagger tutorial how to create golang api documentation using go swagger (1)
Generate
Clients using
Swagger
Documentation
As mentioned above in the beginning,
Swagger isn’t just for API documentation;
we can also generate clients using Swagger.
Let’s see the below example for client
generation for AngularJS.


Example: Client Generation for AngularJS.




npm install ng-swagger-gen --save-dev
sudo node_modules/.bin/ng-swagger-gen -i
../swagger.yaml -o backend/src/app
It will create services files for all the APIs
that are to be included in the Swagger
document. In the same way, you can
generate clients for other frameworks and
technologies.
So, this was about creating Golang API
Documentation using go-swagger. For
complete documentation, please feel free to
visit the github repository: go-swagger-
example
Conclusion
I hope the Go Swagger tutorial was helpful
to you and has cleared your doubts
regarding Swagger Documentation for
Golang APIs. If you are a Golang enthusiast,
please visit the Golang Tutorials page for
more such tutorials and start learning more
each day! Feel free to drop comments and
connect in case you have any questions.


Sometimes many requirements demand
skilled, knowledgeable, and dedicated
developers for their Golang projects. For
such requirements, it is advisable to contact
and hire proficient developers. Are you
looking for such developers for your
projects too? If yes, then why waste time?
Contact Bacancy immediately to hire
Golang developers with fundamental and
advanced Golang knowledge.
Thank You
www.bacancytechnology.com

More Related Content

What's hot (20)

PPTX
What is Swagger?
Philip Senger
 
PPTX
Appium Presentation
OmarUsman6
 
PDF
Developing Faster with Swagger
Tony Tam
 
PDF
Documenting your REST API with Swagger - JOIN 2014
JWORKS powered by Ordina
 
PPT
RESTful API In Node Js using Express
Jeetendra singh
 
PDF
API_Testing_with_Postman
Mithilesh Singh
 
PPTX
Typescript ppt
akhilsreyas
 
PDF
Express node js
Yashprit Singh
 
PPTX
Clean Code
swaraj Patil
 
PPTX
Api Testing
Vishwanath KC
 
PPT
Clean Code summary
Jan de Vries
 
PDF
API Testing
Bikash Sharma
 
PDF
RESTful API 설계
Jinho Yoo
 
PPTX
Angular Data Binding
Duy Khanh
 
PDF
React & GraphQL
Nikolas Burk
 
ODP
OWASP Secure Coding
bilcorry
 
PPTX
Web API 2 Token Based Authentication
jeremysbrown
 
PPTX
Automation With Appium
Knoldus Inc.
 
ODP
Introduction to Swagger
Knoldus Inc.
 
PPTX
Introducing Swagger
Tony Tam
 
What is Swagger?
Philip Senger
 
Appium Presentation
OmarUsman6
 
Developing Faster with Swagger
Tony Tam
 
Documenting your REST API with Swagger - JOIN 2014
JWORKS powered by Ordina
 
RESTful API In Node Js using Express
Jeetendra singh
 
API_Testing_with_Postman
Mithilesh Singh
 
Typescript ppt
akhilsreyas
 
Express node js
Yashprit Singh
 
Clean Code
swaraj Patil
 
Api Testing
Vishwanath KC
 
Clean Code summary
Jan de Vries
 
API Testing
Bikash Sharma
 
RESTful API 설계
Jinho Yoo
 
Angular Data Binding
Duy Khanh
 
React & GraphQL
Nikolas Burk
 
OWASP Secure Coding
bilcorry
 
Web API 2 Token Based Authentication
jeremysbrown
 
Automation With Appium
Knoldus Inc.
 
Introduction to Swagger
Knoldus Inc.
 
Introducing Swagger
Tony Tam
 

Similar to Go swagger tutorial how to create golang api documentation using go swagger (1) (20)

PDF
Meetup 2022 - APIs with Quarkus.pdf
Red Hat
 
PDF
Adding User Management to Node.js
Dev_Events
 
PDF
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
AWS Chicago
 
PPTX
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Dilouar Hossain
 
ODP
An Overview of Node.js
Ayush Mishra
 
PDF
Leveraging Playwright for API Testing.pdf
Steve Wortham
 
PPTX
Nodejs.meetup
Vivian S. Zhang
 
PDF
AEM Sightly Deep Dive
Gabriel Walt
 
PPTX
Mean stack Magics
Aishura Aishu
 
PPTX
UQ21CA642BA1-Unit-3-WAF-Class18-Introduction to Angular Routing.pptx
TamalDey28
 
KEY
How and why i roll my own node.js framework
Ben Lin
 
PDF
NodeJS
LinkMe Srl
 
PPTX
Laravel 5
Sudip Simkhada
 
PDF
JavaScript Modules Done Right
Mariusz Nowak
 
PDF
How to build integrated, professional enterprise-grade cross-platform mobile ...
Appear
 
PDF
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...
Fwdays
 
PDF
Building Automated Data Pipelines with Airflow.pdf
abhaykm804
 
PDF
Mastering Cypress API Testing_ A Comprehensive Guide with Examples.pdf
Steve Wortham
 
PDF
بررسی چارچوب جنگو
railsbootcamp
 
Meetup 2022 - APIs with Quarkus.pdf
Red Hat
 
Adding User Management to Node.js
Dev_Events
 
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
AWS Chicago
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Dilouar Hossain
 
An Overview of Node.js
Ayush Mishra
 
Leveraging Playwright for API Testing.pdf
Steve Wortham
 
Nodejs.meetup
Vivian S. Zhang
 
AEM Sightly Deep Dive
Gabriel Walt
 
Mean stack Magics
Aishura Aishu
 
UQ21CA642BA1-Unit-3-WAF-Class18-Introduction to Angular Routing.pptx
TamalDey28
 
How and why i roll my own node.js framework
Ben Lin
 
NodeJS
LinkMe Srl
 
Laravel 5
Sudip Simkhada
 
JavaScript Modules Done Right
Mariusz Nowak
 
How to build integrated, professional enterprise-grade cross-platform mobile ...
Appear
 
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...
Fwdays
 
Building Automated Data Pipelines with Airflow.pdf
abhaykm804
 
Mastering Cypress API Testing_ A Comprehensive Guide with Examples.pdf
Steve Wortham
 
بررسی چارچوب جنگو
railsbootcamp
 
Ad

More from Katy Slemon (20)

PDF
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
PDF
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
PDF
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
PDF
What’s New in Flutter 3.pdf
Katy Slemon
 
PDF
Why Use Ruby On Rails.pdf
Katy Slemon
 
PDF
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
PDF
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
PDF
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
PDF
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
PDF
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
PDF
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
PDF
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
PDF
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
PDF
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
PDF
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
PDF
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
PDF
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
PDF
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
PDF
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
PDF
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 
Ad

Recently uploaded (20)

PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 

Go swagger tutorial how to create golang api documentation using go swagger (1)

  • 2. Being a developer, you might understand how important it is to document and organize all the APIs, and you also know not every developer likes this documentation part. For that, we need some tools that can be easily used to prepare API documentation. Well, the very first tool that strikes is Swagger.
  • 4. Swagger is a set of open-source tools for writing REST-based APIs. It simplifies the process of writing APIs by notches, specifying the standards & providing the tools required to write and organize scalable APIs.
  • 6. As mentioned before, when we have to follow methodology, documentations are a ‘must.’ With swagger, we can create API documentation by just adding comments in code. Now the question might strike Is Swagger just for API documentation? No, it’s not. With Swagger, we can generate clients for any technologies like Node, AngularJS, PHP, and many more. Thus, it is good for naming conventions, maintaining best practices, and common structure for our application. Also, it does save coding time on the client side. Now, let’s see what we will do in this tutorial.
  • 8. In this tutorial, we will make a demo application and prepare API documentation using go-swagger. Watch the video below to have a look at what we are going to build in this tutorial.
  • 9. Go Swagger Example: How to Create Golang API Documentation
  • 10. Without further ado, let’s get started with the coding part. Here are the step-by-step instructions to create Golang API documentation. Create Project Directory Use the below commands to create a project directory. mkdir goswagger cd goswagger go mod init goswagger
  • 11. Install Swagger download_url=$(curl -s https://api.github.com/repos/go- swagger/go-swagger/releases/latest | jq -r '.assets[] | select(.name | contains("'"$(uname | tr '[:upper:]' '[:lower:]')"'_amd64")) | .browser_download_url') curl -o /usr/local/bin/swagger -L'#' "$download_url" chmod +x /usr/local/bin/swagger Downloading Dependencies Next, we will download the required dependencies For this demo, we will use:
  • 12. Mux: Handling http requests and routing Command: go get github.com/gorilla/mux Swagger: Handling swagger doc Command: go get github.com/go- openapi/runtime/middleware MySQL: Handling MySQL queries Commands: github.com/go-sql-driver/mysql go get github.com/jmoiron/sqlx
  • 13. Import Database company.sql from the Root Directory Create main.go in the root directory. Establish database connection, routing for APIs, and Swagger documentation. r := mux.NewRouter() dbsqlx := config.ConnectDBSqlx() hsqlx := controllers.NewBaseHandlerSqlx(dbsqlx) company := r.PathPrefix("/admin/company").Subrouter() company.HandleFunc("/", hsqlx.PostCompanySqlx).Methods("POST") company.HandleFunc("/", hsqlx.GetCompaniesSqlx).Methods("GET") company.HandleFunc("/{id}", hsqlx.EditCompany).Methods("PUT") company.HandleFunc("/{id}", hsqlx.DeleteCompany).Methods("DELETE")
  • 14. Write Documentation using Go Swagger Now, let’s see how to document using Swagger. It will consist of basic configurations, models, and API routes. Basic Configuration // Comapany Api: // version: 0.0.1 // title: Comapany Api // Schemes: http, https // Host: localhost:5000 // BasePath: / // Produces: // - application/json // // securityDefinitions: // apiKey: // type: apiKey // in: header // name: authorization // swagger:meta package controllers
  • 15. For security definition, we can use the API key, which can be verified for every API. Models Create models for requests and responses for our APIs. Below are some examples of structure with swagger comments. We can add name, type, schema, required, and description for every field. type ReqAddCompany struct { // Name of the company // in: string Name string `json:"name"validate:"required,min=2,max= 100,alpha_space"` // Status of the company // in: int64 Status int64 `json:"status" validate:"required"` }
  • 16. // swagger:parameters admin addCompany type ReqCompanyBody struct { // - name: body // in: body // description: name and status // schema: // type: object // "$ref": "#/definitions/ReqAddCompany" // required: true Body ReqAddCompany `json:"body"` } // swagger:model Company type Company struct { // Id of the company // in: int64 Id int64 `json:"id"` // Name of the company // in: string Name string `json:"name"` // Status of the company // in: int64 Status int64 `json:"status"` }
  • 17. // swagger:model CommonError type CommonError struct { // Status of the error // in: int64 Status int64 `json:"status"` // Message of the error // in: string Message string `json:"message"` } API Routes We can add swagger comments for every route. In which we can specify request and response models, route name, the request method, description, and API key if required.
  • 18. // swagger:route GET /admin/company/ admin listCompany // Get companies list // // security: // - apiKey: [] // responses: // 401: CommonError // 200: GetCompanies func (h *BaseHandlerSqlx) GetCompaniesSqlx(w http.ResponseWriter, r *http.Request) { response := GetCompanies{} companies := models.GetCompaniesSqlx(h.db) response.Status = 1 response.Message = lang.Get("success") response.Data = companies w.Header().Set("content-type", "application/json") json.NewEncoder(w).Encode(response)
  • 19. } // swagger:route POST /admin/company/ admin addCompany // Create a new company // // security: // - apiKey: [] // responses: // 401: CommonError // 200: GetCompany func (h *BaseHandlerSqlx) PostCompanySqlx(w http.ResponseWriter, r *http.Request) { w.Header().Set("content-type", "application/json") response := GetCompany{} decoder := json.NewDecoder(r.Body) var reqcompany *models.ReqCompany err := decoder.Decode(&reqcompany) fmt.Println(err)
  • 20. if err != nil { json.NewEncoder(w).Encode(ErrHandler(la ng.Get("invalid_requuest"))) return } company, errmessage := models.PostCompanySqlx(h.db, reqcompany) if errmessage != "" { json.NewEncoder(w).Encode(ErrHandler(er rmessage)) return } response.Status = 1 response.Message = lang.Get("insert_success") response.Data = company json.NewEncoder(w).Encode(response) }
  • 21. // swagger:route PUT /admin/company/{id} admin editCompany // Edit a company // // consumes: // - application/x-www-form- urlencoded // security: // - apiKey: [] // responses: // 401: CommonError // 200: GetCompany func (h *BaseHandlerSqlx) EditCompany(w http.ResponseWriter, r *http.Request) { r.ParseForm() w.Header().Set("content-type", "application/json") vars := mux.Vars(r) response := GetCompany{}
  • 22. id, err := strconv.ParseInt(vars["id"], 10, 64) if err != nil { json.NewEncoder(w).Encode(ErrHandler(l ang.Get("invalid_requuest"))) return } var reqcompany models.ReqCompany reqcompany.Status, err = strconv.ParseInt(r.FormValue("status"), 10, 64) reqcompany.Name = r.FormValue("name") if err != nil { json.NewEncoder(w).Encode(ErrHandler(l ang.Get("invalid_requuest"))) return }
  • 23. company, errmessage := models.EditCompany(h.db, &reqcompany, id) if errmessage != "" { json.NewEncoder(w).Encode(ErrHandler(er rmessage)) return } response.Status = 1 response.Message = lang.Get("update_success") response.Data = company json.NewEncoder(w).Encode(response) } // swagger:route DELETE /admin/company/{id} admin deleteCompany // Delete company //
  • 24. // security: // - apiKey: [] // responses: // 401: CommonError // 200: CommonSuccess // Create handles Delete get company func (h *BaseHandlerSqlx) DeleteCompany(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) errmessage := models.DeleteCompany(h.db, vars["id"]) if errmessage != "" { json.NewEncoder(w).Encode(ErrHandler(er rmessage)) return } successresponse := CommonSuccess{}
  • 25. successresponse.Status = 1 successresponse.Message = lang.Get("delete_success") w.Header().Set("content-type", "application/json") json.NewEncoder(w).Encode(successrespon se) } After done with api, we can generate swagger yaml or JSON files from swagger comments using the below command in the root directory. swagger generate spec -o ./swagger.yaml – scan-models
  • 26. It will generate a swagger.yaml file in the root directory. We can also create a JSON file the same way. Using this file, we can add routes for documentation in the main.go file. // documentation for developers opts := middleware.SwaggerUIOpts{SpecURL: "/swagger.yaml"} sh := middleware.SwaggerUI(opts, nil) r.Handle("/docs", sh) // documentation for share // opts1 := middleware.RedocOpts{SpecURL: "/swagger.yaml"} // sh1 := middleware.Redoc(opts1, nil) // r.Handle("/docs", sh1)
  • 27. Once you are done with the steps, documentation for developers will look something like the below images. Refer to the below documentation for Read- Only APIs that you want to share with external developers.
  • 30. As mentioned above in the beginning, Swagger isn’t just for API documentation; we can also generate clients using Swagger. Let’s see the below example for client generation for AngularJS. Example: Client Generation for AngularJS. npm install ng-swagger-gen --save-dev sudo node_modules/.bin/ng-swagger-gen -i ../swagger.yaml -o backend/src/app It will create services files for all the APIs that are to be included in the Swagger document. In the same way, you can generate clients for other frameworks and technologies.
  • 31. So, this was about creating Golang API Documentation using go-swagger. For complete documentation, please feel free to visit the github repository: go-swagger- example
  • 33. I hope the Go Swagger tutorial was helpful to you and has cleared your doubts regarding Swagger Documentation for Golang APIs. If you are a Golang enthusiast, please visit the Golang Tutorials page for more such tutorials and start learning more each day! Feel free to drop comments and connect in case you have any questions. Sometimes many requirements demand skilled, knowledgeable, and dedicated developers for their Golang projects. For such requirements, it is advisable to contact and hire proficient developers. Are you looking for such developers for your projects too? If yes, then why waste time? Contact Bacancy immediately to hire Golang developers with fundamental and advanced Golang knowledge.