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(
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)

Spring boot
Spring bootSpring boot
Spring boot
sdeeg
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
Joshua Long
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
Gunith Devasurendra
 
Introducing Swagger
Introducing SwaggerIntroducing Swagger
Introducing Swagger
Tony Tam
 
Swagger APIs for Humans and Robots (Gluecon)
Swagger APIs for Humans and Robots (Gluecon)Swagger APIs for Humans and Robots (Gluecon)
Swagger APIs for Humans and Robots (Gluecon)
Tony Tam
 
Documenting your REST API with Swagger - JOIN 2014
Documenting your REST API with Swagger - JOIN 2014Documenting your REST API with Swagger - JOIN 2014
Documenting your REST API with Swagger - JOIN 2014
JWORKS powered by Ordina
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Jaran Flaath
 
Summer internship report
Summer internship reportSummer internship report
Summer internship report
Ipsit Pradhan
 
Swagger With REST APIs.pptx.pdf
Swagger With REST APIs.pptx.pdfSwagger With REST APIs.pptx.pdf
Swagger With REST APIs.pptx.pdf
Knoldus Inc.
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
Yao Nien Chung
 
Swagger / Quick Start Guide
Swagger / Quick Start GuideSwagger / Quick Start Guide
Swagger / Quick Start Guide
Andrii Gakhov
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
Renato Primavera
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Van Huong
 
Android Internship report presentation
Android Internship report presentationAndroid Internship report presentation
Android Internship report presentation
vinayh.vaghamshi _
 
Writing and using Hamcrest Matchers
Writing and using Hamcrest MatchersWriting and using Hamcrest Matchers
Writing and using Hamcrest Matchers
Shai Yallin
 
Data Sharing Between Child and Parent Components in AngularJS
Data Sharing Between Child and Parent Components in AngularJSData Sharing Between Child and Parent Components in AngularJS
Data Sharing Between Child and Parent Components in AngularJS
Fibonalabs
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
Alex Movila
 
Angular material
Angular materialAngular material
Angular material
Kalpesh Satasiya
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
Saai Vignesh P
 
Spring Boot
Spring BootSpring Boot
Spring Boot
HongSeong Jeon
 
Spring boot
Spring bootSpring boot
Spring boot
sdeeg
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
Joshua Long
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
Gunith Devasurendra
 
Introducing Swagger
Introducing SwaggerIntroducing Swagger
Introducing Swagger
Tony Tam
 
Swagger APIs for Humans and Robots (Gluecon)
Swagger APIs for Humans and Robots (Gluecon)Swagger APIs for Humans and Robots (Gluecon)
Swagger APIs for Humans and Robots (Gluecon)
Tony Tam
 
Documenting your REST API with Swagger - JOIN 2014
Documenting your REST API with Swagger - JOIN 2014Documenting your REST API with Swagger - JOIN 2014
Documenting your REST API with Swagger - JOIN 2014
JWORKS powered by Ordina
 
Summer internship report
Summer internship reportSummer internship report
Summer internship report
Ipsit Pradhan
 
Swagger With REST APIs.pptx.pdf
Swagger With REST APIs.pptx.pdfSwagger With REST APIs.pptx.pdf
Swagger With REST APIs.pptx.pdf
Knoldus Inc.
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
Yao Nien Chung
 
Swagger / Quick Start Guide
Swagger / Quick Start GuideSwagger / Quick Start Guide
Swagger / Quick Start Guide
Andrii Gakhov
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
Renato Primavera
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Van Huong
 
Android Internship report presentation
Android Internship report presentationAndroid Internship report presentation
Android Internship report presentation
vinayh.vaghamshi _
 
Writing and using Hamcrest Matchers
Writing and using Hamcrest MatchersWriting and using Hamcrest Matchers
Writing and using Hamcrest Matchers
Shai Yallin
 
Data Sharing Between Child and Parent Components in AngularJS
Data Sharing Between Child and Parent Components in AngularJSData Sharing Between Child and Parent Components in AngularJS
Data Sharing Between Child and Parent Components in AngularJS
Fibonalabs
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
Alex Movila
 

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

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

More from Katy Slemon (20)

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

Recently uploaded (20)

Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 

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.