SlideShare une entreprise Scribd logo
1  sur  34
Télécharger pour lire hors ligne
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.
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

Contenu connexe

Tendances

An Introduction To Jenkins
An Introduction To JenkinsAn Introduction To Jenkins
An Introduction To JenkinsKnoldus Inc.
 
Setting up MySQL Replication Cluster in Kubernetes
Setting up MySQL Replication Cluster in KubernetesSetting up MySQL Replication Cluster in Kubernetes
Setting up MySQL Replication Cluster in KubernetesElizabeth Yu, MBA
 
Using Xcore with Xtext
Using Xcore with XtextUsing Xcore with Xtext
Using Xcore with XtextHolger Schill
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: NotesRoberto Casadei
 
Bootiful Development with Spring Boot and React
Bootiful Development with Spring Boot and ReactBootiful Development with Spring Boot and React
Bootiful Development with Spring Boot and ReactVMware Tanzu
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3 ArezooKmn
 
Intro to Docker November 2013
Intro to Docker November 2013Intro to Docker November 2013
Intro to Docker November 2013Docker, Inc.
 
Do we need Unsafe in Java?
Do we need Unsafe in Java?Do we need Unsafe in Java?
Do we need Unsafe in Java?Andrei Pangin
 
Dart and Flutter Basics.pptx
Dart and Flutter Basics.pptxDart and Flutter Basics.pptx
Dart and Flutter Basics.pptxDSCVSSUT
 
Vue js 大型專案架構
Vue js 大型專案架構Vue js 大型專案架構
Vue js 大型專案架構Hina Chen
 
Create Development and Production Environments with Vagrant
Create Development and Production Environments with VagrantCreate Development and Production Environments with Vagrant
Create Development and Production Environments with VagrantBrian Hogan
 
DevOpsDays Taipei 2019 - Mastering IaC the DevOps Way
DevOpsDays Taipei 2019 - Mastering IaC the DevOps WayDevOpsDays Taipei 2019 - Mastering IaC the DevOps Way
DevOpsDays Taipei 2019 - Mastering IaC the DevOps Waysmalltown
 
Finding Your Way in Container Security
Finding Your Way in Container SecurityFinding Your Way in Container Security
Finding Your Way in Container SecurityKsenia Peguero
 
What is jenkins
What is jenkinsWhat is jenkins
What is jenkinslinuxdady
 
From Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdfFrom Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdfJosé Paumard
 
Ansible presentation
Ansible presentationAnsible presentation
Ansible presentationSuresh Kumar
 
An intro to Kubernetes operators
An intro to Kubernetes operatorsAn intro to Kubernetes operators
An intro to Kubernetes operatorsJ On The Beach
 
Dev Containers Spring 2023.pptx
Dev Containers Spring 2023.pptxDev Containers Spring 2023.pptx
Dev Containers Spring 2023.pptxDawn Wages
 

Tendances (20)

An Introduction To Jenkins
An Introduction To JenkinsAn Introduction To Jenkins
An Introduction To Jenkins
 
Setting up MySQL Replication Cluster in Kubernetes
Setting up MySQL Replication Cluster in KubernetesSetting up MySQL Replication Cluster in Kubernetes
Setting up MySQL Replication Cluster in Kubernetes
 
Using Xcore with Xtext
Using Xcore with XtextUsing Xcore with Xtext
Using Xcore with Xtext
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
Bootiful Development with Spring Boot and React
Bootiful Development with Spring Boot and ReactBootiful Development with Spring Boot and React
Bootiful Development with Spring Boot and React
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3
 
Intro to Docker November 2013
Intro to Docker November 2013Intro to Docker November 2013
Intro to Docker November 2013
 
Gradle
GradleGradle
Gradle
 
Do we need Unsafe in Java?
Do we need Unsafe in Java?Do we need Unsafe in Java?
Do we need Unsafe in Java?
 
Dart and Flutter Basics.pptx
Dart and Flutter Basics.pptxDart and Flutter Basics.pptx
Dart and Flutter Basics.pptx
 
Vue js 大型專案架構
Vue js 大型專案架構Vue js 大型專案架構
Vue js 大型專案架構
 
Intro to Terraform
Intro to TerraformIntro to Terraform
Intro to Terraform
 
Create Development and Production Environments with Vagrant
Create Development and Production Environments with VagrantCreate Development and Production Environments with Vagrant
Create Development and Production Environments with Vagrant
 
DevOpsDays Taipei 2019 - Mastering IaC the DevOps Way
DevOpsDays Taipei 2019 - Mastering IaC the DevOps WayDevOpsDays Taipei 2019 - Mastering IaC the DevOps Way
DevOpsDays Taipei 2019 - Mastering IaC the DevOps Way
 
Finding Your Way in Container Security
Finding Your Way in Container SecurityFinding Your Way in Container Security
Finding Your Way in Container Security
 
What is jenkins
What is jenkinsWhat is jenkins
What is jenkins
 
From Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdfFrom Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdf
 
Ansible presentation
Ansible presentationAnsible presentation
Ansible presentation
 
An intro to Kubernetes operators
An intro to Kubernetes operatorsAn intro to Kubernetes operators
An intro to Kubernetes operators
 
Dev Containers Spring 2023.pptx
Dev Containers Spring 2023.pptxDev Containers Spring 2023.pptx
Dev Containers Spring 2023.pptx
 

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

Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to SwaggerKnoldus Inc.
 
Meetup 2022 - APIs with Quarkus.pdf
Meetup 2022 - APIs with Quarkus.pdfMeetup 2022 - APIs with Quarkus.pdf
Meetup 2022 - APIs with Quarkus.pdfRed Hat
 
Adding User Management to Node.js
Adding User Management to Node.jsAdding User Management to Node.js
Adding User Management to Node.jsDev_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/burbsAWS 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.jsAyush Mishra
 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep DiveGabriel Walt
 
cdac@parag.gajbhiye@test123
cdac@parag.gajbhiye@test123cdac@parag.gajbhiye@test123
cdac@parag.gajbhiye@test123Parag Gajbhiye
 
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 frameworkBen Lin
 
JavaScript Modules Done Right
JavaScript Modules Done RightJavaScript Modules Done Right
JavaScript Modules Done RightMariusz 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
 
بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگوrailsbootcamp
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteorSapna Upreti
 
Operator SDK for K8s using Go
Operator SDK for K8s using GoOperator SDK for K8s using Go
Operator SDK for K8s using GoCloudOps2005
 

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

Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to Swagger
 
Meetup 2022 - APIs with Quarkus.pdf
Meetup 2022 - APIs with Quarkus.pdfMeetup 2022 - APIs with Quarkus.pdf
Meetup 2022 - APIs with Quarkus.pdf
 
Adding User Management to Node.js
Adding User Management to Node.jsAdding User Management to Node.js
Adding User Management to Node.js
 
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
 
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...
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.js
 
What is Swagger?
What is Swagger?What is Swagger?
What is Swagger?
 
Nodejs.meetup
Nodejs.meetupNodejs.meetup
Nodejs.meetup
 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep Dive
 
cdac@parag.gajbhiye@test123
cdac@parag.gajbhiye@test123cdac@parag.gajbhiye@test123
cdac@parag.gajbhiye@test123
 
Mean stack Magics
Mean stack MagicsMean stack Magics
Mean stack Magics
 
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
 
NodeJS
NodeJSNodeJS
NodeJS
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
JavaScript Modules Done Right
JavaScript Modules Done RightJavaScript Modules Done Right
JavaScript Modules Done Right
 
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 ...
 
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...
 
بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگو
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
 
Operator SDK for K8s using Go
Operator SDK for K8s using GoOperator SDK for K8s using Go
Operator SDK for K8s using Go
 

Plus de 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.pdfKaty 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.pdfKaty 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.pdfKaty 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.pdfKaty Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfKaty 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.pdfKaty 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.pdfKaty 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.pdfKaty 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.pdfKaty 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.pdfKaty 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.pdfKaty 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.pdfKaty 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.pdfKaty 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.pdfKaty 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.pdfKaty 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.pdfKaty 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.pdfKaty 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.pdfKaty 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.pdfKaty 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.pdfKaty Slemon
 

Plus de 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
 
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
 
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
 
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
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 

Dernier

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 

Dernier (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 

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.
  • 28.
  • 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.