Building a RESTful API with Go

Hey my Golang looks good right?

Go is an open source programming language that makes it easy to build simple, reliable, and efficient software. Go was created at Google in 2007 by Robert Grisemer, Rob Pike and Ken Thompson. Go is a compiled, statically typed language.

PS: This article is not an introduction to the Go programming language, its an intermediate one.

For the purpose of this tutorial, we’ll be creating a RESTful API for a Phone Book app.

REST, RESTful, WTH!!

REST is an acronym for Representational State Transfer. It is a web standards architecture and HTTP Protocol. The REST protocol, decribes six (6) constraints:

Uniform Interface

Cacheable

Client-Server

Stateless

Code on Demand

Layered System

REST is composed of methods such as a base URL, media types, etc. RESTful applicaitons uses HTTP requests to perform the CRUD operations.

Setup

To start up writing our API, we need to setup our environment. Get the Latest Release of Go (as of this writing, its 1.8.3 ) > here. Once you’ve installed Go, you should have a $GOPATH sys variable set. We need a Project directory to store our source, we make one:

$ mkdir -p $GOPATH/src/github/{your username}/rest-api

The command, will create a rest-api project folder in your Go home.

$ cd rest-api

Next we create a main.go file

Router

We’ll need to use a mux to route requests, so we need a Go package for that (mux stands for HTTP request multiplexer which matches an incoming request to against a list of routes (registered)). In the rest-api directory, lets require the dependency (package rather).

Building the file again shouldn’t return any errors, but the functions are empty. Each methods, take two parameters w and r which are of types http.ResponseWriter and *http.Request. These two parameters are populated once hit by a request.

Pull all data from the Phonebook

Lets write the code to get all records tires screech»> We don’t have any data… yeah, lets populate manually (databases are out of scope for this tutorial). Lets add a Person struct (think of it as an object) and an Address struct, and a people variable to populate with.

Testing

Conclusion

You just saw how to build a very simple RESTful API using the Go programming language. While we used mock data instead of a database, we saw how to create endpoints that do various operations with JSON data and GoLang slices. Did I miss anything important? Let me know in the comments.

PHDevConnect is a free, open community of Port Harcourt based Developers, UI / UX Designers, Project managers, Architects etc who can create their own digital team or join other teams for paid/open sourced projects.

Never miss a story from PH DevConnect, when you sign up for Medium. Learn more