BUILD A SIMPLE RESTFUL API USING GOLANG AND CASSANDRA

Sinai Nday
6 min readAug 17, 2020

--

Photo by Clément H on Unsplash

To better understand this tutorial, please make sure you have some knowledge about go and Cassandra. if not, try to learn some go and cassandra commands before continuing with this article.

Golang or Go is a fast-growing programming language, it was created by Google and has become popular for its simplicity. Today it’s used for fast speed, concurrency, and parallelism. We have amazing projects built in Go such as Docker, Kubernetes, Ethereum, hyberledger fabric, terraform, etc... that’s why I chose Golang for this tutorial, and most importantly because I am very comfortable when programming in Go🙂.

What about Cassandra? well, Apache Cassandra is one of the most widely used, proven, and robust distributed databases. Cassandra is a powerful NoSQL database, it’s faster and scalable. Netflix, Facebook, Cisco Webex are some of the companies that use Cassandra DB.

Ok, let’s get started.

The architecture looks something like this.

Sorry, I am not a good designer😎.

The Restful API uses HTTP requests to GET, PUT, POST, and DELETE data. An API for a website is a code that allows two software programs to communicate with each other. On top of CRUD functions, any other functions can be added accordingly.

1. Install Go

To install Go, You can go straight and download it to the official website here, and the instructions on how to install it can be found here.
In this tutorial, I will be using Ubuntu 16.04, feel free to install it on any OS of your choice.

let’s check if we have Golang installed by typing Go in the terminal

Notice that Go is not installed, so let’s install it now. here are the commands:

> sudo add-apt-repository ppa:longsleep/golang-backports 
> sudo apt-get update
> sudo apt-get install golang-go
> go version
> go

Now Go is installed, let’s go ahead and install Apache Cassandra.

2. Install Apache Cassandra

> echo "deb https://downloads.apache.org/cassandra/debian 311x main" | sudo tee -a /etc/apt/sources.list.d/cassandra.sources.list
> curl https://downloads.apache.org/cassandra/KEYS | sudo apt-key add -
> sudo apt-get update
> sudo apt-get install cassandra

All the instructions can be found here.

To check if Cassandra is up and running, exit from being root and run

> service cassandra status

Notice that Cassandra is running.

If Cassandra is not running, try to run

> service cassandra restart

Now let’s connect to Cassandra and create a keyspace that contains one table.

> cqlsh
> CREATE KEYSPACE restfulapi WITH replication = {‘class’: ‘SimpleStrategy’, ‘replication_factor’: 1};
> USE restfulapi;
> CREATE TABLE students ( id int PRIMARY KEY , firstname text ,lastname text, age int );

We are running Cassandra locally and not in the production environment, thus the keyspace is created with class SimpleStrategy and 1 replication.

3. Program the Restful API

Our Restful API will implement the following functions:

CREATE a student: Create or insert a particular student into Cassandra DB
RETRIEVE all students: Get all the students from the database
RETRIEVE a student: Get a particular student from the database
DELETE a student: Erase any student from the database
DELETE all students: Erase all students in the database
UPDATE a student: Update the student info
COUNT the total number of students.

Open up any IDE that supports Go and create a folder named restfulapi and add the following files: Server.go, AllFuncs.go, Type.go, and Cassandra.go.

We need to download some useful packages, open the terminal, and use these commands to download these 3 packages :

> go get "github.com/gorilla/handlers"
> go get "github.com/gorilla/mux"
> go get "github.com/gocql/gocql"

Get back to those files that We created earlier.

a.Cassandra.go
Let’s start by connecting our go program to Cassandra DB using Gocql

We firstly imported the gocql package from GitHub, then We connected to Cassandra DB using the local address. Remember the keyspace we created previously? 😐 good!! here We specified that keyspace and created a new session.

b. Type.go

Here we created a structure that represents our data, We also exported all the fields. make sure every single variable in the structure starts with a capital letter, otherwise, go won’t be able to export the field.

c.AllFuncs.go

Let’s define all the functions for each request. We’re gonna use very simple Cassandra commands and Go HTTP package to handle all the upcoming HTTP requests, in this tutorial we are using gorilla mux that implements a request router and dispatcher for matching incoming requests to their respective handler.

c. Server.go

Let’s now handle those functions and add CORS using gorilla http handlers

Notice that we implemented the CORS (Cross-Origin Resource Sharing ) from line 22 to 25 because we would like to allow any application to use freely all the API functions, if these lines are skipped, then none of the applications will use the restful API.

4. Run our code
Navigate to the created folder restfulapi and run

> go build 

An executable named restfulapi has been created, now open a terminal and run it :

> ./restfulapi

Open the browser and type localhost:3000

Let’s now test all the functions using postman.

5. Test the API

Let’s test our API using Postman

  • Create a student
    Create as many as you can
  • Get all the student

In the browser:

  • Delete a student

check whether the student is deleted

  • Count the total number of students
  • Update a student

check in the browser

  • Get a student
  • Delete all the students

Check in the browser

The result is null because there is no data.

6. To do

- Secure the API using JWT or other solutions
- Add more functions to the API
- Consume the API using any front-end frameworks: VueJS, AngularJS, ReactJS, etc.

Hope this can help someone.
The source code can be found on
Github, fork it, download, and enjoy!!!
The same principle can be used for any DB, find the example for MariaDB
here

--

--

Sinai Nday
Sinai Nday

Responses (1)