grequests – a REST API package for Go

The developers who worked on Python know about the Requests library. It is a clean, short library that is not included in the standard library of Python. The Go package grequests is inspired by that library. It provides a simple set of functions, using which we can make API requests such as GET, POST, PUT, and DELETE from our Go code. Using grequests allows us to encapsulate the inbuilt HTTP request and response. To install the grequests package for your Go, run the following command:

go get -u github.com/levigross/grequests

Now, see this basic program illustrating the use of the grequests library to make a GET request to a REST API. Create a directory called grequests in your Go source directory and add a file called basicRequest.go, as shown in the following code snippet:

package main

import (
  "github.com/levigross/grequests"
  "log"
)

func main() {
  resp, err := grequests.Get("http://httpbin.org/get", nil)
  // You can modify the request by passing an optional RequestOptions struct
  if err != nil {
    log.Fatalln("Unable to make request: ", err)
  }
  log.Println(resp.String())
}

The grequests package has methods for performing all REST actions. The preceding program uses the Get function from the package. It takes two function arguments. The first one is the URL of the API, and the second one is the request parameters object. Since we are not passing any request parameters, the second argument is nil here. resp is returned from the request, and it has a function called String() that returns the response body: 

go run grequests/basicRequest.go

The output is the JSON response returned by the httpbin:

{
"args": {},
"headers": {
"Accept-Encoding": "gzip",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "GRequests/0.10"
},
"origin": "116.75.82.9",
"url": "http://httpbin.org/get"
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.83.199