What is Golang REST API?

What is REST API?

REST (Representational State Transfer) API (Application Programming Interface) is used to deliver user functionality when dealing with websites. HTTP requests are used to communicate with REST APIs so users can navigate a URL website. These URLs can return certain information that is stored as part of the API. Any changes to data or information is done by accessing the database of that particular API’s URL. Most APIs these days would return a response to us in the form of JSON.

Working of RESP API
Working of RESP API

Golang REST API

REST APIs can be created easily in the GO language by creating a simple server to handle HTTP requests. First, create a .go file in golang. Let’s create three functions Home(), handleReq() and the main() function:

  • the Home() function is used to automatically redirect the API to the output provided by the Home() function.
  • the handleReq() function can be used to handle all the URL requests. This function will contain dependencies based on URLs and the calls to their respective functions. This function will match the URL path with a defined function.
  • The main() function is used to start running the API.
package main
// important libraries
import (
    "fmt"
    "log"
    "net/http"
)
// Home function
func Home()(w http.ResponseWriter, r *http.Request){
// This is what the function will print.
    fmt.Fprintf(w, "Welcome to Educative Home!")
    
}
// function to handle requests
func handleReq() {
// will call Home function by default. 
    http.HandleFunc("/", Home)
    log.Fatal(http.ListenAndServe(":8200", nil))
}

func main() {
// starting the API
    handleReq()
}

If you run this application in browser with the following URL, you will get the output shown below:

svg viewer

Let’s extend this by creating another endpoint. We will edit the code above to create another function, return_contact().

package main
// important libraries
import (
"fmt"
"log"
"net/http"
)
// Home function
func Home()(w http.ResponseWriter, r *http.Request){
// This is what the function will print.
fmt.Fprintf(w, "Welcome to Educative Home!")
}
func return_contact()(w http.ResponseWriter, r *http.Request){
// This is what the function will print.
fmt.Fprintf(w, "Email: support@educative.io")
}
// function to handle requests
func handleReq() {
// will call Home function by default.
http.HandleFunc("/", Home)
http.HandleFunc("/contact", return_contact)
log.Fatal(http.ListenAndServe(":8200", nil))
}
func main() {
// starting the API
handleReq()
}

Now, a user can access the endpoint contact by typing and entering the following URL:

http://localhost:8200/contact
svg viewer

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved