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

PDF
Json web token
PDF
Service workers
PPT
Angular 8
PDF
Introduction to GitHub Actions
PPTX
Angular js PPT
PDF
The Enterprise Case for Node.js
PDF
Tools for Solving Performance Issues
PPTX
Spring Boot
Json web token
Service workers
Angular 8
Introduction to GitHub Actions
Angular js PPT
The Enterprise Case for Node.js
Tools for Solving Performance Issues
Spring Boot

What's hot (20)

PDF
Die ultimative Anleitung für HCL Nomad Web Administratoren
PDF
Introduction to Node.JS Express
PDF
Building Event Driven (Micro)services with Apache Kafka
PPTX
final-technical-roadmap-aap-2 ansible redhat
PPTX
What is context? How to use context in Odoo by weblearns
PDF
Microservices - Death of the Enterprise Service Bus (ESB)? (Update 2016)
PPTX
PPTX
Joomla and cms
PDF
NestJS
KEY
Introduction to Django
PPTX
Introduction to Node.js
PPTX
Spring boot
PDF
Intro to Github Actions @likecoin
PPTX
Angular
PDF
gRPC in Go
PPT
Monitoring using Prometheus and Grafana
PPTX
Bare Metal Cluster with Kubernetes, Istio and Metallb | Nguyen Phuong An, Ngu...
PDF
Kubernetes Node Deep Dive
PPTX
Android Deep Linking
Die ultimative Anleitung für HCL Nomad Web Administratoren
Introduction to Node.JS Express
Building Event Driven (Micro)services with Apache Kafka
final-technical-roadmap-aap-2 ansible redhat
What is context? How to use context in Odoo by weblearns
Microservices - Death of the Enterprise Service Bus (ESB)? (Update 2016)
Joomla and cms
NestJS
Introduction to Django
Introduction to Node.js
Spring boot
Intro to Github Actions @likecoin
Angular
gRPC in Go
Monitoring using Prometheus and Grafana
Bare Metal Cluster with Kubernetes, Istio and Metallb | Nguyen Phuong An, Ngu...
Kubernetes Node Deep Dive
Android Deep Linking
Ad

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

PPTX
Grails with swagger
PDF
Streamlining API with Swagger.io
PDF
Swagger Notes.pdf
PDF
Swagger With REST APIs.pptx.pdf
PDF
Swagger / Quick Start Guide
ODP
Introduction to Swagger
PPTX
Rest API with Swagger and NodeJS
PPTX
Swagger - make your API accessible
PPTX
dod-api-meetup-03262015-swagger-docs
PPTX
API Docs with OpenAPI 3.0
PDF
Get Your Node.js API Swaggering with OpenAPI Spec
PPTX
What is Swagger?
PPTX
Document your rest api using swagger - Devoxx 2015
PPTX
Everybody loves Swagger
PDF
Creating API documentation for international communities
PPTX
Swagger APIs for Humans and Robots (Gluecon)
PDF
Designing APIs with Swagger and OpenAPI 1st Edition Joshua S. Ponelat
PPTX
API Design first with Swagger
PDF
Developing Faster with Swagger
Grails with swagger
Streamlining API with Swagger.io
Swagger Notes.pdf
Swagger With REST APIs.pptx.pdf
Swagger / Quick Start Guide
Introduction to Swagger
Rest API with Swagger and NodeJS
Swagger - make your API accessible
dod-api-meetup-03262015-swagger-docs
API Docs with OpenAPI 3.0
Get Your Node.js API Swaggering with OpenAPI Spec
What is Swagger?
Document your rest api using swagger - Devoxx 2015
Everybody loves Swagger
Creating API documentation for international communities
Swagger APIs for Humans and Robots (Gluecon)
Designing APIs with Swagger and OpenAPI 1st Edition Joshua S. Ponelat
API Design first with Swagger
Developing Faster with Swagger
Ad

More from Katy Slemon (20)

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

Recently uploaded (20)

PDF
5-Ways-AI-is-Revolutionizing-Telecom-Quality-Engineering.pdf
PDF
Transform-Quality-Engineering-with-AI-A-60-Day-Blueprint-for-Digital-Success.pdf
PPTX
Module 1 Introduction to Web Programming .pptx
PDF
The influence of sentiment analysis in enhancing early warning system model f...
DOCX
Basics of Cloud Computing - Cloud Ecosystem
PPTX
AI IN MARKETING- PRESENTED BY ANWAR KABIR 1st June 2025.pptx
PDF
INTERSPEECH 2025 「Recent Advances and Future Directions in Voice Conversion」
PDF
Transform-Your-Supply-Chain-with-AI-Driven-Quality-Engineering.pdf
DOCX
search engine optimization ppt fir known well about this
PPTX
Training Program for knowledge in solar cell and solar industry
PDF
Improvisation in detection of pomegranate leaf disease using transfer learni...
PDF
Rapid Prototyping: A lecture on prototyping techniques for interface design
PDF
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
PDF
Co-training pseudo-labeling for text classification with support vector machi...
PDF
Lung cancer patients survival prediction using outlier detection and optimize...
PPT
Galois Field Theory of Risk: A Perspective, Protocol, and Mathematical Backgr...
PDF
4 layer Arch & Reference Arch of IoT.pdf
PDF
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PDF
Transform-Your-Factory-with-AI-Driven-Quality-Engineering.pdf
5-Ways-AI-is-Revolutionizing-Telecom-Quality-Engineering.pdf
Transform-Quality-Engineering-with-AI-A-60-Day-Blueprint-for-Digital-Success.pdf
Module 1 Introduction to Web Programming .pptx
The influence of sentiment analysis in enhancing early warning system model f...
Basics of Cloud Computing - Cloud Ecosystem
AI IN MARKETING- PRESENTED BY ANWAR KABIR 1st June 2025.pptx
INTERSPEECH 2025 「Recent Advances and Future Directions in Voice Conversion」
Transform-Your-Supply-Chain-with-AI-Driven-Quality-Engineering.pdf
search engine optimization ppt fir known well about this
Training Program for knowledge in solar cell and solar industry
Improvisation in detection of pomegranate leaf disease using transfer learni...
Rapid Prototyping: A lecture on prototyping techniques for interface design
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
Co-training pseudo-labeling for text classification with support vector machi...
Lung cancer patients survival prediction using outlier detection and optimize...
Galois Field Theory of Risk: A Perspective, Protocol, and Mathematical Backgr...
4 layer Arch & Reference Arch of IoT.pdf
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
Taming the Chaos: How to Turn Unstructured Data into Decisions
Transform-Your-Factory-with-AI-Driven-Quality-Engineering.pdf

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.