[go: up one dir, main page]

0% found this document useful (0 votes)
4 views15 pages

Golang Json

This document is a tutorial on building a simple JSON-based REST API in Golang, focusing on managing a library of books. It covers the setup of the Go environment, creating endpoints for viewing, adding, updating, and deleting books, and using the Gorilla Mux package for routing. The tutorial provides code snippets and instructions for testing the API using Postman.

Uploaded by

milos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views15 pages

Golang Json

This document is a tutorial on building a simple JSON-based REST API in Golang, focusing on managing a library of books. It covers the setup of the Go environment, creating endpoints for viewing, adding, updating, and deleting books, and using the Gorilla Mux package for routing. The tutorial provides code snippets and instructions for testing the API using Postman.

Uploaded by

milos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Build a simple Json based REST API in Golang | b... https://medium.com/@rehanjaved237/build-a-simp...

You have 1 free story left this month. Sign up and get an extra one for free.

Build a simple Json based REST API


in Golang
Rehan Javed Follow
Aug 3 · 5 min read

Photo by Tianyi Ma on Unsplash

1 of 15 8/31/20, 1:56 PM
Build a simple Json based REST API in Golang | b... https://medium.com/@rehanjaved237/build-a-simp...

This tutorial will help you understand and build an API in Golang. In
this tutorial we well be building a REST API that will allow the users
to view, add, update and delete books in a library. The final source
code is available on Github.

. . .

Prerequisites:
We assume that you already have the latest version of Go Installed.
In case you don’t have installed it, check out this tutorial.

Getting Started:
First of all start be creating a folder called rest-api can move into the
newly created directly.

$ mkdir rest-api

$ cd rest-api

Now create the main.go file. This will be the entry point of our
application.

$ touch main.go

2 of 15 8/31/20, 1:56 PM
Build a simple Json based REST API in Golang | b... https://medium.com/@rehanjaved237/build-a-simp...

Open the main.go file in your text editor. In case you have Vs-Code
Installed, run this command.

$ code main.go

By now main.go file should be opened in Vs-Code. Now define the


main package and write a small test program to see if everything is
working fine.

hello-world program - Golang hosted with ❤ by GitHub view raw

1 package main
2
3 import ("fmt")
4
5 func main() {
6 fmt.Println("Hello World");
7 }

Now to test it. Run the following commands.

$ go run main.go

Expected Results:

3 of 15 8/31/20, 1:56 PM
Build a simple Json based REST API in Golang | b... https://medium.com/@rehanjaved237/build-a-simp...

$ Hello World

So by now we have created a simple hello-world program in golang.


main is the package where we deploy our executable programs. It
tells that the program should compile as an executable program
rather than a shared library. func main() is the function name that
acts as the entry point of the application.

Setting up the HTTP Server using Gorilla


Mux:
The name mux stands for “HTTP request multiplexer”. Gorilla Mux is
an opensource package that implements the request router and
dispatcher for matching incoming requests to their respective
handlers. To use it you first need to install it. Run the following
commands to install the Gorilla Mux package.

$ go get -u github.com/gorilla/mux

Now by using Gorilla Mux we will be implementing our first home


endpoint “/”.

4 of 15 8/31/20, 1:56 PM
Build a simple Json based REST API in Golang | b... https://medium.com/@rehanjaved237/build-a-simp...

1 package main
2
3 import (
4 "fmt"
5 "log"
6 "net/http"
7
8 "github.com/gorilla/mux"
9 )
10
11 func home(w http.ResponseWriter, r *http.Request) {
12 fmt.Fprintf(w, "<h1>Congrats. Run Successfully!</h1>")
13 }
14
15 func main() {
16 router := mux.NewRouter().StrictSlash(true)
17 router.HandleFunc("/", home)
18 log.Fatal(http.ListenAndServe(":8080", router))

Following output should be seen whenever the “/” endpoint will be


hit on url http://localhost:8080/. Following output should be
observed whenever this http://localhost:8080/ will be hit.

5 of 15 8/31/20, 1:56 PM
Build a simple Json based REST API in Golang | b... https://medium.com/@rehanjaved237/build-a-simp...

Install a tool named POSTMAN. It is one of the most famous API


testing tools. It will help you to communicate and send requests to
your API.

Working on our REST API:


Now, if you have installed POSTMAN and you are done with the past
steps than we are ready to go for the API development.

- Create a dummy database


We are creating a dummy database that will be containing some of
the already present books in the library.

6 of 15 8/31/20, 1:56 PM
Build a simple Json based REST API in Golang | b... https://medium.com/@rehanjaved237/build-a-simp...

1 // A global variable that is incremented everytime a book is added.


2 // Used for providing a unique ID to each book
3 var count int
4
5 // Book Struct
6 type Book struct {
7 ID int `json:"id"`
8 Isbn string `json:"isbn"`
9 Title string `json:"title"`
10 Author *Author `json:"author"`
11 }
12
13 // Author Struct
14 type Author struct {
15 FirstName string `json:"firstname"`
16 LastName string `json:"lastname"`
17 }
18
19 // A slice that will contain the books

The `json:"name"` term indicate how each name will be interpreted


when converting back and forth in Json.

The slice books will contain all the books. We he reading, adding,
updating and deleting data from this slice via the API calls.

- View All Books:

7 of 15 8/31/20, 1:56 PM
Build a simple Json based REST API in Golang | b... https://medium.com/@rehanjaved237/build-a-simp...

1 // Give all the books


2 func getBooks(w http.ResponseWriter, r *http.Request) {
3 w.Header().Set("Content-Type", "application/json")
4
5 json.NewEncoder(w).Encode(books)
6 }

view raw

The line w.Header().Set("Content-Type", "application/json")

updates the header and tells the receiving system that the Content-
Type of the data it is going to receive will be in the Json Format.

The expected result in PostMan is:

8 of 15 8/31/20, 1:56 PM
Build a simple Json based REST API in Golang | b... https://medium.com/@rehanjaved237/build-a-simp...

In case you don’t write w.Header().Set("Content-Type",

"application/json") the output will be like this:

As you can see, the receiving system won’t be able to interpret that the
data it received is in JSON.

- View a single Book based on its ID:

9 of 15 8/31/20, 1:56 PM
Build a simple Json based REST API in Golang | b... https://medium.com/@rehanjaved237/build-a-simp...

1 // Give a book with some ID


2 func getBook(w http.ResponseWriter, r *http.Request) {
3 w.Header().Set("Content-Type", "application/json")
4 vars := mux.Vars(r)
5
6 for _, book := range books {
7 if strconv.Itoa(book.ID) == vars["id"] {
8 json.NewEncoder(w).Encode(book)
9 return
10 }
11 }
12
13 json.NewEncoder(w).Encode(&Book{})
14 }

The endpoint for this call is /api/books/{id} and uses a GET method.
By using the Gorilla Mux we get the value of “id” and after filtering
that book we display a specific book as a response to the user. In case
the book of that id is not present that we send back an empty book
indicating that this record is not found.

The expected result in Postman is:

10 of 15 8/31/20, 1:56 PM
Build a simple Json based REST API in Golang | b... https://medium.com/@rehanjaved237/build-a-simp...

- Add a new Book

1 // Adds a new Book


2 func addBook(w http.ResponseWriter, r *http.Request) {
3 w.Header().Set("Content-Type", "application/json")
4
5 var book Book
6 _ = json.NewDecoder(r.Body).Decode(&book)
7
8 book.ID = count
9 count++
10
11 books = append(books, book)
12
13 json.NewEncoder(w).Encode(book)
14 }

11 of 15 8/31/20, 1:56 PM
Build a simple Json based REST API in Golang | b... https://medium.com/@rehanjaved237/build-a-simp...

The endpoint for this call is /api/books and uses a POST method. The
data received is decoded and added into the Book object. The object is
later appended to the books slice. The book which is successfully
added is displayed to the user.

The expected output after sending a POST request from Postman is as


follows:

- Update an existing book based on ID

12 of 15 8/31/20, 1:56 PM
Build a simple Json based REST API in Golang | b... https://medium.com/@rehanjaved237/build-a-simp...

1 // Updates a book with some ID


2 func updateBook(w http.ResponseWriter, r *http.Request) {
3 w.Header().Set("Content-Type", "application/json")
4 vars := mux.Vars(r)
5
6 var tempBook Book
7 for index, book := range books {
8 if strconv.Itoa(book.ID) == vars["id"] {
9 _ = json.NewDecoder(r.Body).Decode(&tempBook)
10 tempBook.ID = index
11 books[index] = tempBook
12 json.NewEncoder(w).Encode(books[index])
13 return
14 }
15 }
16
17 json.NewEncoder(w).Encode(&Book{})
18 }

The endpoint for this call is /api/books/{id} and uses the PUT
request. By using the Gorilla Mux we get the value of “id” and after
filtering that book we replace it with the newly provided book.

The expected output after sending a PUT request from Postman is as


follows:

Golang Restful Api Json Api Web Development API

13 of 15 8/31/20, 1:56 PM
Build a simple Json based REST API in Golang | b... https://medium.com/@rehanjaved237/build-a-simp...

Discover
Welcome to a place where
words matter. On
smart voices and original
ideas take center stage - w
no ads in sight.

- Delete a book based on its ID

The endpoint for this call is /api/books/{id} and uses the Delete request. By
using the Gorilla Mux we get the value of “id” and after filtering that book we
remove it from the slice. If a book is found and removed successfully than the
content of that book is displayed to the user or else an empty book is displayed.

The expected output after sending a DELETE request from Postman is as follows:

14 of 15 8/31/20, 1:56 PM
Build a simple Json based REST API in Golang | b... https://medium.com/@rehanjaved237/build-a-simp...

Preparing the routes


Now combining all the routes, we get:

Complete Code:
This is the complete project code in case you want to have a look.

15 of 15 8/31/20, 1:56 PM

You might also like