Golang REST API – Getting Started

Golang REST API 1

Hello, tiny Gophers. Welcome to a new article segment on building a REST API using Go. I will try to make this a series so that it covers everything that is needed by you to make your own. This is the first part. Links will be provided at the end of this segment to the next article. So, let’s get this going!

What is the REST API?

It stands for Representational State Transfer Application Programming Interface. And while that may be a mouthful, all company websites need to use some form of REST API to allow for functionality such as querying for information.

I have written previously that graphs are much better at the same operations than REST, and that slowly everyone will adopt it. And while that may be the case, REST APIs have flooded the website development world for the past decade and are not going anywhere anytime soon. Also, if you don’t know how the wheel works, you wouldn’t know how the bike works.

Consider a website where we have lots of books. we can query the REST interface for information. Say you want all books by the author “Robert A Heinlein” that have been published in the year 1941, you’ll get a collection of 11 book titles. If you want to see an example for fetching book details using an interface, go to this tutorial for graphs.

In fact, this interfacing is so useful, it allows us to embed book windows from Google books API into our own webpages:

<!DOCTYPE html "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google Books Embedded Viewer API Example</title>
    <script type="text/javascript" src="https://www.google.com/books/jsapi.js"></script>
    <script type="text/javascript">
      google.books.load();

      function initialize() {
        var viewer = new google.books.DefaultViewer(document.getElementById('viewerCanvas'));
        viewer.load('ISBN:0738531367');
      }

      google.books.setOnLoadCallback(initialize);
    </script>
  </head>
  <body>
    <div id="viewerCanvas" style="width: 600px; height: 500px"></div>
  </body>
</html>

If you don’t have a HTML file ready to embed this in, you can just simply view the example here:

https://developers-dot-devsite-v2-prod.appspot.com/books/docs/viewer/examples/book-simple

You can also check out their other examples, but you get the point.

Typically we send HTTP requests to an URL that we have defined in our REST API and it would either perform a given task for us or return a certain bit of data. Most APIs these days would return a response to us in the form of JSON.

Short Note on JSON

It stands for JavaScript Object Notation, which acts as a means of sending and receiving all information, and thankfully Go comes with some excellent support for encoding and decoding these formats using the standard library package, encoding/JSON.

Basic Structure of HTTP Server

Moving on to the basic structure of the HTTP server which we shall be used to query from. This is the same as the one taught in our previous tutorial on Http:

import (
    "fmt"
    "log"
    "net/http"
)

func homePage(w http.ResponseWriter, r *http.Request){
    fmt.Fprintf(w, "Welcome to the HomePage!")
    fmt.Println("Endpoint Hit: homePage")
}

func handleRequests() {
    http.HandleFunc("/", homePage)
    log.Fatal(http.ListenAndServe(":8000", nil))
}

func main() {
    handleRequests()
}

This is our main.go file for the server. We would like to describe 3 different functions within this main.go file – A homePage function that manages all requests for our root URL, a handleRequests function that matches the hit URL path with a given function, and the main function that will launch our API.

So now if we run this, we get a webpage at localhost:8000 saying “Welcome to the HomePage!”

Article struct for JSON Response

Now let’s define our Article structure for querying inside the main.go file. We also create a global array called Articles, which we will populate through our main function. This will be similar to a database:

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
)

// Article ...
type Article struct {
	Title  string `json:"Title"`
	Author string `json:"author"`
	Link   string `json:"link"`
}

// Articles ...
var Articles []Article

func homePage(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Welcome to the HomePage!")
	fmt.Println("Endpoint Hit: homePage")
}

func handleRequests() {
	http.HandleFunc("/", homePage)
	// add our articles route and map it to our
	// returnAllArticles function like so
	http.HandleFunc("/articles", returnAllArticles)
	log.Fatal(http.ListenAndServe(":8000", nil))
}

func returnAllArticles(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Endpoint Hit: returnAllArticles")
	json.NewEncoder(w).Encode(Articles)
}

func main() {
	Articles = []Article{
		Article{Title: "Python Intermediate and Advanced 101",
			Author: "Arkaprabha Majumdar",
			Link:   "https://www.amazon.com/dp/B089KVK23P"},
		Article{Title: "R programming Advanced",
			Author: "Arkaprabha Majumdar",
			Link:   "https://www.amazon.com/dp/B089WH12CR"},
		Article{Title: "R programming Fundamentals",
			Author: "Arkaprabha Majumdar",
			Link:   "https://www.amazon.com/dp/B089S58WWG"},
	}
	handleRequests()
}
  • Article struct contains 3 properties we need to represent all of the articles on our site – Title, Author, and Link. Of course, we can add more in a similar manner.
  • We made a new function called returnAllArticles, which will do the simple task of returning our newly populated Articles variable, encoded in JSON format.
  • The call to JSON.NewEncoder(w).Encode(article) does the job of encoding our articles array into a JSON string and then writing as part of our response.
  • Before this will work, we’ll also need to add a new route to our handleRequests function that will map any calls to http://localhost:8000/articles to our newly defined function.

Now, if you go run the file, then at localhost:8000/articles, you’ll find a list of three books that I have written, and which are excellent books for Python and R programming.

Rest Api Golang Output In Server
Rest Api Golang Output In Server

That’s it for this section. Fiddle around with this, and make your own json formats.

Next we’ll be looking at working with a gorrilla/mux router in Golang Mux Router.