Building a RESTful API with Go

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. In this tutorial, we will build a simple REST API using Go. 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.

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.

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. At the top of the file, add the following code:

package main

import (
  "encoding/json"
  "log"
  "math/rand"
  "net/http"
)

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. This function will also be our Http Handler Function so the function definition will include a http.ResponseWriter and an *http.request. Inside the function, a credit score will be generated, passed into the credit_rating struct, and then written to the HTTP response as a JSON object. The implemented function will go below the other credit score definition code and will look like this:

func getCreditScore(w http.ResponseWriter, r *http.Request) {
  var creditRating = credit_rating{
      CreditRating: (rand.Intn(creditScoreMax-creditScoreMin) + creditScoreMin)
  }

  w.WriteHeader(http.StatusOK)
  json.NewEncoder(w).Encode(creditRating)
}

Lastly, we will add a main function where our application will execute and a handleRequests function which will create our endpoint and expose our API service on port 8080. The code will look like this:

func handleRequests() {
  http.Handle("/creditscore", http.HandlerFunc(getCreditScore))
  log.Fatal(http.ListenAndServe(":8080", nil))
}

func main() {
  handleRequests()
}

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

package main

import (
  "encoding/json"
  "log"
  "math/rand"
  "net/http"
)

const creditScoreMin = 500
const creditScoreMax = 900

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

func getCreditScore(w http.ResponseWriter, r *http.Request) {
  var creditRating = credit_rating{
      CreditRating: (rand.Intn(creditScoreMax-creditScoreMin) + creditScoreMin)
  }

  w.WriteHeader(http.StatusOK)
  json.NewEncoder(w).Encode(creditRating)
}

func handleRequests() {
  http.Handle("/creditscore", http.HandlerFunc(getCreditScore))
  log.Fatal(http.ListenAndServe(":8080", nil))
}

func main() {
  handleRequests()
}

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. 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. 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!

Learn More About Moesif Use API analytics to grow your API 14 day free trial. No credit card required. Learn More
Monetize APIs with Moesif Monetize APIs with Moesif

Monetize APIs with Moesif

Learn More