In this post we will build simple REST API’s using the Go programming language. We will also be using the MUX Router. I will also explain some of the fundamentals of the language for beginners.
If you want to learn Go visit awesome-go-in-education. A curated list of resources about Go in Education. If you want to do the same but in Python read A simple guide to creating REST API’s with flask. I will be using Goland from jetbrains as my IDE.
Before we get started, a few jargon.
REST: a RESTful API uses HTTP requests to GET, PUT, POST and DELETE data.
RESTful API designing: guidelines is a must read before you continue. It talks about terminologies, endpoints, versioning status codes and so much more.
Test your environment
Let us first test the environment to check if everything is working fine. For that we will be using a simple “Hello World” program.
Once that is done, let us import necessary packages.
Performing imports
Let us look at the imports used one by one.
- encoding/json – since our API’s communications will be handled in JSON format
- log – will log errors
- net/http – We will use this package to create the API’s and communicate using HTTP protocols.
- mux – A powerful URL router and dispatcher for golang . A router is used to define which function will run when a particular endpoint(URL) is called.
Writing the main funciton
Do note In Go, := is for declaration + assignment, whereas = is for assignment only.For example, var foo int = 10 is the same as foo := 10.
- First we create a new variable for our multiplexer.
- Then we use
HandleFunc
to define which function will handle which API endpoint. - With
http.ListenAndServe
we define the port that your program must listen to continuously.We wrap that aroundlog.Fatal
so that all exeptions are logged.
To run your code type the following in your console
go run main.go
If you face an error telling you that mux is not installed then run
go get -u github.com/gorilla/mux in your console.
Post Requests
Let us now post some data to the server.
Note: Click here to know more about json in Go.
- Adding a new function and a function handler.
2. Creating structs that will hold our json data.
3. Writing our add function.
Putting it all together
Hope this post helped you. If you want more help, feel free to ping me @Ashish_che