When it comes to building an API, Go is an extremely popular programming language choice to build powerful RESTful APIs with. 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”. In this tutorial, we 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:
- Install Go
- Have an IDE to edit your code
- 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.
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, 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:
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.
`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:
`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:
func main() {
router := gin.Default()
router.GET("/creditscore", getCreditScore)
router.Run("localhost:8080")
}
The completed code in the main.go file, combined together, will look like this.
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.
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.
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. For a solution to your API analytics and monetization needs, check out Moesif today to explore all of this and more!
Top comments (0)