Go Resty is a Go language library for building RESTful API clients. With Go Resty, developers can build reliable RESTful API clients more quickly and efficiently. This chapter introduces how to quickly get started with Go Resty.

Installation

require github.com/go-resty/resty/v2 v2.7.0

or

go get github.com/go-resty/resty/v2

Resty Example

The following examples will help you to use the resty library as comfortably as possible.

// Import resty into your code and reference it as `resty`.
import "github.com/go-resty/resty/v2"

Simple GET Request

// Create a Resty client
client := resty.New()

resp, err := client.R().
    EnableTrace().
    Get("https://httpbin.org/get")

// Explore response object
fmt.Println("Response Info:")
fmt.Println("  Error      :", err)
fmt.Println("  Status code:", resp.StatusCode())
fmt.Println("  Status     :", resp.Status())
fmt.Println("  Protocol   :", resp.Proto())
fmt.Println("  Time       :", resp.Time())
fmt.Println("  Received at:", resp.ReceivedAt())
fmt.Println("  Body       :\n", resp)
fmt.Println()

// Explore tracking information
fmt.Println("Request trace info:")
ti := resp.Request.TraceInfo()
fmt.Println("  DNS lookup      :", ti.DNSLookup)
fmt.Println("  Connect time    :", ti.ConnTime)
fmt.Println("  TCP connect time:", ti.TCPConnTime)
fmt.Println("  TLS handshake   :", ti.TLSHandshake)
fmt.Println("  Server time     :", ti.ServerTime)
fmt.Println("  Response time   :", ti.ResponseTime)
fmt.Println("  Total time      :", ti.TotalTime)
fmt.Println("  Is conn reused  :", ti.IsConnReused)
fmt.Println("  Conn was idle   :", ti.IsConnWasIdle)
fmt.Println("  Conn idle time  :", ti.ConnIdleTime)
fmt.Println("  Request attempt :", ti.RequestAttempt)
fmt.Println("  Remote address  :", ti.RemoteAddr.String())
Output
Response Info:
  Error      : 
  Status code: 200
  Status     : 200 OK
  Protocol   : HTTP/2.0
  Time       : 457.034718ms
  Received at: 2020-09-14 15:35:29.784681 -0700 PDT m=+0.458137045
  Body       :
  {
    "args": {},
    "headers": {
      "Accept-Encoding": "gzip",
      "Host": "httpbin.org",
      "User-Agent": "go-resty/2.4.0 (https://github.com/go-resty/resty)",
      "X-Amzn-Trace-Id": "Root=1-5f5ff031-000ff6292204aa6898e4de49"
    },
    "origin": "0.0.0.0",
    "url": "https://httpbin.org/get"
  }

Request trace info:
  DNS lookup      : 4.074657ms
  Connect time    : 381.709936ms
  TCP connect time: 77.428048ms
  TLS handshake   : 299.623597ms
  Server time     : 75.414703ms
  Response time   : 79.337µs
  Total time      : 457.034718ms
  Is conn reused  : false
  Conn was idle   : false
  Conn idle time  : 0s
  Request attempt : 1
  Remote address  : 3.221.81.55:443

Complex GET Request

// Create a Resty client
client := resty.New()

// Set query parameters
resp, err := client.R().
      SetQueryParams(map[string]string{
          "page_no": "1",
          "limit": "20",
          "sort":"name",
          "order": "asc",
          "random":strconv.FormatInt(time.Now().Unix(), 10),
      }).
      SetHeader("Accept", "application/json").
      SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F").
      Get("/search_result")


// Example using Request.SetQueryString method
resp, err := client.R().
      SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more").
      SetHeader("Accept", "application/json").
      SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F").
      Get("/show_product")


// If necessary, force the specified response content type to instruct Resty to parse JSON response into your struct
resp, err := client.R().
      SetResult(result).
      ForceContentType("application/json").
      Get("v2/alpine/manifests/latest")

Various POST Request Examples

// Create a Resty client
client := resty.New()

// POST JSON string
// If client-level settings have been set, the content type does not need to be set
resp, err := client.R().
      SetHeader("Content-Type", "application/json").
      SetBody(`{"username":"testuser", "password":"testpass"}`).
      SetResult(&AuthSuccess{}).    // or SetResult(AuthSuccess{}).
      Post("https://myapp.com/login")

// POST []byte array
// If client-level settings have been set, the content type does not need to be set
resp, err := client.R().
      SetHeader("Content-Type", "application/json").
      SetBody([]byte(`{"username":"testuser", "password":"testpass"}`)).
      SetResult(&AuthSuccess{}).    // or SetResult(AuthSuccess{}).
      Post("https://myapp.com/login")

// POST struct, default to JSON content type, no need to set
resp, err := client.R().
      SetBody(User{Username: "testuser", Password: "testpass"}).
      SetResult(&AuthSuccess{}).    // or SetResult(AuthSuccess{}).
      SetError(&AuthError{}).       // or SetError(AuthError{}).
      Post("https://myapp.com/login")

// POST map, default to JSON content type, no need to set
resp, err := client.R().
      SetBody(map[string]interface{}{"username": "testuser", "password": "testpass"}).
      SetResult(&AuthSuccess{}).    // or SetResult(AuthSuccess{}).
      SetError(&AuthError{}).       // or SetError(AuthError{}).
      Post("https://myapp.com/login")

// Upload file as raw byte array. Example: Upload a file to Dropbox
fileBytes, _ := os.ReadFile("/Users/jeeva/mydocument.pdf")

// Note that we do not set the content type header because go-resty will automatically detect the Content-Type
resp, err := client.R().
      SetBody(fileBytes).
      SetContentLength(true).          // Dropbox requires this value
      SetAuthToken("").
      SetError(&DropboxError{}).       // or SetError(DropboxError{}).
      Post("https://content.dropboxapi.com/1/files_put/auto/resty/mydocument.pdf") // DropBox also supports PUT method uploads

// Note: If the content type header is not set, resty will detect the Content-Type of the request body
//   * For struct and map data types, it defaults to 'application/json'
//   * Then it is the normal text content type

PUT Request

You can use various combinations of the PUT method call just like demonstrated for POST.

// Note: This is an example of using the PUT method, for more combinations please refer to POST

// Create a Resty client
client := resty.New()

// Send request with JSON content type
// If there are client-level settings, authentication token can be omitted, error
resp, err := client.R().
      SetBody(Article{
        Title: "go-resty",
        Content: "This is my article content, oh yeah!",
        Author: "Jeevanandam M",
        Tags: []string{"article", "example", "resty"},
      }).
      SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
      SetError(&Error{}).       // Or SetError(Error{}).
      Put("https://myapp.com/article/1234")

PATCH Request

You can use various combinations of the PATCH method call just like demonstrated for POST.

// Note: This is an example of using the PATCH method, for more combinations please refer to POST

// Create a Resty client
client := resty.New()

// Send request with JSON content type
// If there are client-level settings, authentication token can be omitted, error
resp, err := client.R().
      SetBody(Article{
        Tags: []string{"new tag 1", "new tag 2"},
      }).
      SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
      SetError(&Error{}).       // Or SetError(Error{}).
      Patch("https://myapp.com/articles/1234")

DELETE, HEAD, OPTIONS Request

// Create a Resty client
client := resty.New()

// Delete an article
// If there are client-level settings, authentication token can be omitted, error
resp, err := client.R().
      SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
      SetError(&Error{}).       // Or SetError(Error{}).
      Delete("https://myapp.com/articles/1234")

// Delete multiple articles with JSON string as payload/content
// If there are client-level settings, authentication token can be omitted, error
resp, err := client.R().
      SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
      SetError(&Error{}).       // Or SetError(Error{}).
      SetHeader("Content-Type", "application/json").
      SetBody(`{article_ids: [1002, 1006, 1007, 87683, 45432] }`).
      Delete("https://myapp.com/articles")

// Get the header information of a resource
// If there are client-level settings, authentication token can be omitted
resp, err := client.R().
      SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
      Head("https://myapp.com/videos/hi-res-video")

// Get the options information of a resource
// If there are client-level settings, authentication token can be omitted
resp, err := client.R().
      SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
      Options("https://myapp.com/servers/nyc-dc-01")

Setting up JSON and XML Serialization/Deserialization Operations

Users can register their chosen JSON/XML libraries with resty, or write their own libraries. By default, resty registers the standard encoding/json and encoding/xml libraries.

// Example of registering json-iterator
import jsoniter "github.com/json-iterator/go"

json := jsoniter.ConfigCompatibleWithStandardLibrary

client := resty.New().
    SetJSONMarshaler(json.Marshal).
    SetJSONUnmarshaler(json.Unmarshal)

// Similarly, users can set up XML as follows -
client.SetXMLMarshaler(xml.Marshal).
    SetXMLUnmarshaler(xml.Unmarshal)