Introducing Restful APIs in GO
In case you are landing here directly, it’s strongly suggested that you go and read through this for fundamentals.
In this blog, we shall be looking at following concepts :-
- Reading JSON in GO.
- Hitting an RESTful GET API in GO.
- Hitting an RESTful POST API in GO.
- Exposing and hosting Simple Restful API in GO.
Question :- What are the possible ways of encoding the messages ?
Answer:- When you’re working in a distributed environment usually over the network you send and receive messages. Messages can be encoded in various formats such as : json, messages pack, particle buffer, XML and more.
Question :- Which format is more widely accepted ?
- Json is a good default since it’s widely used in many languages and services supported.
- Json can also easily be passed from the browser making it the preferred encoding is Rest APIs.
Question :- What’s the take of GO with regards to handling JSON ?
Answer:- Go comes with a built in encoding/json library. We can either encode the code to IO reader, IO writer or work with byte slices.
Question :- Demonstrate any use-case of reading JSONs with GO ?
Answer:- Say you are running an online bank, you get request for withdraw & deposit money and you need to pass them and handle them.
Step #1.) Here is how our JSON request looks like :-
Step #2.) Let’s define the corresponding request structure which mimics the the json object.
- All the fields must start with an uppercase.
- Another crucial thing is to indicate the json’s field mapping with this structure. So, we have Login string and then we use a field tag to say to json that in json the name of this field is user.
- Similarly, we have the Type and we say to the json this is a lower case type in the json.
- And again the Amount which is the lowercase amount in the json.
Step #3.) In our main program we perform following works :-
- Create a NewBufferedString from bytes. This create an object of reader that we can use with the json decoder.
- Next, we create a json NewDecoder with a reader.
- Then, we create an empty request and then ask the decoder to decode the request.
- And if the decode resulted in an error we use log.Fatalf to print error and abort the program. Otherwise we print what we got.
Question :- Demonstrate any use-case of generating the JSONs with GO ?
Answer:- We would continue with our above use-case itself and generate an JSON based output :-
Step #1.) Here are dependencies we would be importing. Don’t forget to import the OS package :-
Step #2.) Next, here is how the code looks like :-
- At line #42, we’re going to create a response where the keys are strings and the value is empty interface (In Go, it means any type).
- Now, we create a NewEncoder for the standard output just to print it out and we encode the response. And of course if there is an error in the encoding, we’re going to use log.fatalf to print it out.
Question :- How do services usually communicates ?
- A common way to communicate between services is by using HTTP and JSON, also known as REST API.
- HTTP plus JSON is very common, and chances are you’ll have to work with them at one point or another.
Question :- Does there exists any inbuilt support for http calls in GO ?
Answer:- You’ll find most of what you need in the package net/http.
Question :- Let’s start making a GET request in GO ?
- We’ll use the httpbin.org/get service, to test your HTTP client.
- We do an http.Get to above mentioned URL.
- At line #13, we get the response and an error. If there is an error, we use log.Fatalf to exit the program.
- At line #17, make sure to close the response body. We use defer to make sure the response body is closed.
- Finally, we’re just going to print out what the server sent us, using io.Copy from the response body to standard output.
Question :- Let’s make a post request with the JSON body in GO.
Step #1.) :- We define a Job structure, the User, the Action, and how many times you want the action to be performed.
Step #2.) In our main function (as shown in below snapshot):-
- At line #22, we are going to create a new Job object.
- At line #28, we create bytes.buffer, we use a JSON encoder with the buffer, and we encode the job inside the in memory buffer, and if there is an error, we exit.
- The http post function will cause the request body to be io.writer. We’re going to use bytes with buffer, which is an in memory writer or reader.
- In the http.Post method, we tell it what is the url that we want to hit to, we tell it the content type, and it’s really important for a lot of APIs to send the right content type, and we send the in memory buffer which now will be an io.reader.
- Now, if there is an error making the post request, we are going to fail, and again, defer the Body.Close, and copy the output to standard output.
Question :- Can we launch RESTful APIs in GO ?
Answer:- Go comes with a powerful HTTP server in the standard library. It’s easy to build the REST APIs with it. We write handler functions to expose APIs.
Question :- Whats an Handler Function in GO ?
Answer:- A handler function is a function that gets following parameters :-
- http.ResponseWriter where you write the response to. Since the http.ResponseWriter implements io.writer, we can use the Fprintf to print the output to it.
- A pointer to an http.Request, which represents the current request.
Question :- Demonstrate the process of exposing a Restful API in GO ?
Step #1.) Following are the libraries we would be importing :-
Step #2.) We need to mount the endpoint to the Handler. This means that every time someone accesses /hello on our web server, helloHandler is going to get called.
And now, we tell the HTTP server to listen and serve on port 8080. This is potentially an endless loop. But if there is an error, it will exit with an error value. And in our case, we’re going to print out the error and exit the program.
Step #3.) Here is how the code of handler function looks like :-
Step #4.) Let’s save it and run it. We built a production-ready HTTP server in 20 lines of code. I find it pretty impressive.
That’s all in this section. If you liked reading this blog, kindly do press on clap button multiple times, to indicate your appreciation. We would see you in next series.