DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How To Create a Stub in 5 Minutes
  • Build a REST API With Just 2 Classes in Java and Quarkus
  • Micronaut vs Spring Boot: A Detailed Comparison
  • Container Checkpointing in Kubernetes With a Custom API

Trending

  • AI, ML, and Data Science: Shaping the Future of Automation
  • Why Database Migrations Take Months and How to Speed Them Up
  • *You* Can Shape Trend Reports: Join DZone's Software Supply Chain Security Research
  • How to Build Local LLM RAG Apps With Ollama, DeepSeek-R1, and SingleStore
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Building a RESTful API With Go and Gin

Building a RESTful API With Go and Gin

Looking to build a simple REST API with Go and Gin? Check out our tutorial to build one in minutes.

By 
Matt Tanner user avatar
Matt Tanner
·
Feb. 20, 23 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
2.0K Views

Join the DZone community and get the full member experience.

Join For Free

When it comes to building an API, Go is an extremely popular programming language choice to build powerful RESTful APIs. The language is super lightweight, has many different libraries and frameworks available, and is easy to run. One of the frameworks supported by Go is Gin. Gin is a web framework written in Golang that offers great performance and scalability, amongst other features. According to the Gin website, “Gin features a Martini-like API, but with performance up to 40 times faster than Martini”. This tutorial will build a simple REST API using Go and Gin. The API endpoint will allow a user to retrieve a credit score rating. Of course, we won’t be linking up to any backend systems to pull a credit score but will instead use a random number generator to generate the score and return it to the user. Although simple, this tutorial will show you the basics of REST API development with Go and Gin.

Prerequisites

Before we start, we must ensure that a couple of prerequisites are completed. To follow along and run this tutorial, you will need to:

  1. Install Go
  2. Have an IDE to edit your code
  3. Install Postman so that you can test the endpoint

After all 3 of these prerequisites are completed, we can begin!

Creating the Base Project

In the directory of your choice, Create a folder named my-go-rest-api.

With the new folder created, open a terminal in the root of the folder so that commands can be executed to build and run our go project.

Once your terminal is pointed to the root directory of your project, run the go mod init command so you can initialize the go project and manage the dependencies.

Shell
 
go mod init example/my-go-rest-api


Lastly, in the root directory, create a file called main.go. This will be the file where we write all of our code.

Adding in the Code

Once the main.go file is created, and we can add our application code to it. First, we will add a few lines of code to import our dependencies, including our dependency for Gin. At the top of the file, add the following code:

Go
 
package main

import (
   "math/rand"
   "net/http"
   "github.com/gin-gonic/gin"
)


Next, under the imports code, we will add in our upper and lower bounds for generating the “credit score” and create a credit_rating struct to hold our credit rating data.

Go
 
const creditScoreMin = 500
const creditScoreMax = 900

type credit_rating struct {
  CreditRating int `json:"credit_rating"`
}


With the parameters for our credit score defined, we will create a function that will randomly generate a credit score number. Inside the function, which receives a *gin.Context struct, a credit score will be generated, passed into the credit_rating struct, and then written to the gin.Context as a JSON object. The implemented function will go below the other credit score definition code and will look like this:

Go
 
func getCreditScore(c *gin.Context) {
    var creditRating = credit_rating{
      CreditRating: (rand.Intn(creditScoreMax-creditScoreMin) + creditScoreMin)
    }

    c.IndentedJSON(http.StatusOK, creditRating)
}


Lastly, we will add a main function where our application will expose a GET endpoint for /creditscore and expose our API service on port 8080 (the default port for Gin). The code will look like this:

Go
 
func main() {
   router := gin.Default()
   router.GET("/creditscore", getCreditScore)

   router.Run("localhost:8080")
}


The completed code is in the main.go file, combined together, will look like this.

Go
 
package main

import (
   "math/rand"
   "net/http"
   "github.com/gin-gonic/gin"
)

const creditScoreMin = 500
const creditScoreMax = 900

type credit_rating struct {
   CreditRating int `json:"credit_rating"`
}

func getCreditScore(c *gin.Context) {
    var creditRating = credit_rating{
      CreditRating: (rand.Intn(creditScoreMax-creditScoreMin) + creditScoreMin)
    }

    c.IndentedJSON(http.StatusOK, creditRating)
}

func main() {
   router := gin.Default()
   router.GET("/creditscore", getCreditScore)

   router.Run("localhost:8080")
}

Running and Testing the Code

With our code finally written, in the current folder, run go get in order to pull the packages and dependencies into the project.

Shell
 
go get .


After the command is completed, the project dependencies will be available to our code when we run it. Now, let’s run our simple web API by using the go run command in the root directory of the app.

Shell
 
go run .


Now, our API is up and running. You can send a test HTTP request through Postman, or another service of your choice. By sending a request to localhost:8080/creditscore, you should see a 200 OK status code and a credit score returned from the random number generator we created in the getCreditScore handler. For this test, no request body is needed for the incoming request.

Wrapping Up

With that, we’ve created a simple RESTful API using Go and Gin. This code can then be expanded on as needed to build APIs for your applications. Moving forward, you may want to secure the API with an API key, integrate the API with an API gateway, check out how your API is being consumed and used, or build revenue through API monetization.

API REST Go (programming language) POST (HTTP)

Published at DZone with permission of Matt Tanner. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Create a Stub in 5 Minutes
  • Build a REST API With Just 2 Classes in Java and Quarkus
  • Micronaut vs Spring Boot: A Detailed Comparison
  • Container Checkpointing in Kubernetes With a Custom API

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!