rest

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 8, 2016 License: MIT Imports: 4 Imported by: 366

README

Build Status GoDoc

HTTP REST client, simplified for Go

Here is a quick example:

GET /your/api/{param}/call

package main

import "github.com/sendgrid/rest"
import "fmt"

func main() {
	const host = "https://api.example.com"
	endpoint := "/your/api/" + param + "/rest"
	baseURL := host + endpoint
	requestHeaders := make(map[string]string)
	requestHeaders["Authorization"] = "Bearer " + Key
	method := rest.Get
	request := rest.Request{
		Method:         method,
		BaseURL:        baseURL,
		RequestHeaders: requestHeaders,
	}
	response, err := rest.API(request)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(response.StatusCode)
		fmt.Println(response.ResponseBody)
		fmt.Println(response.ResponseHeaders)
	}
}

POST /your/api/{param}/call with headers, query parameters and a request body.

package main

import "github.com/sendgrid/rest"
import "fmt"

func main() {
	const host = "https://api.example.com"
	endpoint := "/your/api/" + param + "/rest"
	baseURL := host + endpoint
	requestHeaders := make(map[string]string)
	requestHeaders["Authorization"] = "Bearer " + Key
	requestHeaders["X-Test"] = "Test"
	var requestBody = []byte(`{"some": 0, "awesome": 1, "data": 3}`)
	queryParams := make(map[string]string)
	queryParams["hello"] = 0
	queryParams["world"] = 1
	method := "POST"
	request = rest.Request{
		Method:         method,
		BaseURL:        baseURL,
		RequestHeaders: requestHeaders,
		QueryParams:    queryParams,
		RequestBody:    requestBody,
	}
	response, err := rest.API(request)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(response.StatusCode)
		fmt.Println(response.ResponseBody)
		fmt.Println(response.ResponseHeaders)
	}
}

Installation

go get github.com/sendgrid/rest

Usage

Following is an example using SendGrid. You can get your free account here.

First, update your environment with your SENDGRID_API_KEY and HOST. For this example HOST=https://api.sendgrid.com.

echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env

Following is an abridged example, here is the full working code.

package main

import (
	"encoding/json"
	"fmt"
	"github.com/sendgrid/rest"
	"os"
)

func main() {

	// Build the URL
	const host = "https://api.sendgrid.com"
	endpoint := "/v3/api_keys"
	baseURL := host + endpoint

	// Build the request headers
	key := os.Getenv("SENDGRID_API_KEY")
	requestHeaders := make(map[string]string)
	requestHeaders["Content-Type"] = "application/json"
	requestHeaders["Authorization"] = "Bearer " + key

	// GET Collection
	method := rest.Get

	// Build the query parameters
	queryParams := make(map[string]string)
	queryParams["limit"] = "100"
	queryParams["offset"] = "0"

	// Make the API call
	request := rest.Request{
		Method:         method,
		BaseURL:        baseURL,
		RequestHeaders: requestHeaders,
		QueryParams:    queryParams,
	}
	response, err := rest.API(request)

	// POST
	method = rest.Post

	var requestBody = []byte(` {
        "name": "My API Key",
        "scopes": [
            "mail.send",
            "alerts.create",
            "alerts.read"
        ]
    }`)
	request = rest.Request{
		Method:         method,
		BaseURL:        baseURL,
		RequestHeaders: requestHeaders,
		QueryParams:    queryParams,
		RequestBody:    requestBody,
	}
	response, err = rest.API(request)

	// Get a particular return value.
	// Note that you can unmarshall into a struct if
	// you know the JSON structure in advance.
	b := []byte(response.ResponseBody)
	var f interface{}
	err = json.Unmarshal(b, &f)
	if err != nil {
		fmt.Println(err)
	}
	m := f.(map[string]interface{})
	apiKey := m["api_key_id"].(string)

	// GET Single
	method = rest.Get

	// Make the API call
	request = rest.Request{
		Method:         method,
		BaseURL:        baseURL + "/" + apiKey,
		RequestHeaders: requestHeaders,
	}
	response, err = rest.API(request)

	// PATCH
	method = rest.Patch

	requestBody = []byte(`{
        "name": "A New Hope"
    }`)
	request = rest.Request{
		Method:         method,
		BaseURL:        baseURL + "/" + apiKey,
		RequestHeaders: requestHeaders,
		RequestBody:    requestBody,
	}
	response, err = rest.API(request)

	// PUT
	method = rest.Put

	requestBody = []byte(`{
        "name": "A New Hope",
        "scopes": [
            "user.profile.read",
            "user.profile.update"
        ]
    }`)
	request = rest.Request{
		Method:         method,
		BaseURL:        baseURL + "/" + apiKey,
		RequestHeaders: requestHeaders,
		RequestBody:    requestBody,
	}
	response, err = rest.API(request)

	// DELETE
	method = rest.Delete

	request = rest.Request{
		Method:         method,
		BaseURL:        baseURL + "/" + apiKey,
		RequestHeaders: requestHeaders,
		QueryParams:    queryParams,
		RequestBody:    requestBody,
	}
	response, err = rest.API(request)
}

Announcements

[2016.04.05] - We hit version 1!

Roadmap

Milestones

How to Contribute

We encourage contribution to our libraries, please see our CONTRIBUTING guide for details.

About

![SendGrid Logo] (https://assets3.sendgrid.com/mkt/assets/logos_brands/small/sglogo_2015_blue-9c87423c2ff2ff393ebce1ab3bd018a4.png)

rest is guided and supported by the SendGrid Developer Experience Team.

rest is maintained and funded by SendGrid, Inc. The names and logos for python-http-client are trademarks of SendGrid, Inc.

Documentation

Overview

Package rest allows for quick and easy access any REST or REST-like API.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddQueryParameters

func AddQueryParameters(baseURL string, queryParams map[string]string) string

AddQueryParameters adds query paramaters to the URL

func BuildRequestObject

func BuildRequestObject(request Request) (*http.Request, error)

BuildRequestObject creates the HTTP request object

func MakeRequest

func MakeRequest(req *http.Request) (*http.Response, error)

MakeRequest makes the API call

Types

type Method added in v1.0.2

type Method string

Method contains the supported HTTP verbs

const (
	Get    Method = "GET"
	Post   Method = "POST"
	Put    Method = "PUT"
	Patch  Method = "PATCH"
	Delete Method = "DELETE"
)

type Request

type Request struct {
	Method         Method
	BaseURL        string // e.g. https://api.sendgrid.com
	RequestHeaders map[string]string
	QueryParams    map[string]string
	RequestBody    []byte
}

Request holds the request to an API Call Currently, only GET, PUT, PATCH, POST and DELETE are supported methods

type Response

type Response struct {
	StatusCode      int                 // e.g. 200
	ResponseBody    string              // e.g. {"result: success"}
	ResponseHeaders map[string][]string // e.g. map[X-Ratelimit-Limit:[600]]
}

Response holds the response from an API call

func API

func API(request Request) (*Response, error)

API is the main interface to the API.

func BuildResponse

func BuildResponse(res *http.Response) (*Response, error)

BuildResponse builds the response struct

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL