postman

package module
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2022 License: MIT Imports: 5 Imported by: 12

README

go-postman-collection

Mentioned in Awesome Go GoDoc Build Status Report Code coverage

Go module to work with Postman Collections.

This module aims to provide a simple way to work with Postman collections. Using this module, you can create collections, update them and export them into the Postman Collection format v2 (compatible with Insomnia)

Postman Collections are a group of saved requests you can organize into folders. For more information about Postman Collections, you can visit the official documentation.

Examples

Collections
Read a Postman Collection
package main

import (
	"os"

	postman "github.com/rbretecher/go-postman-collection"
)

func main() {
	file, err := os.Open("postman_collection.json")
	defer file.Close()

	if err != nil {
		panic(err)
	}

	c, err := postman.ParseCollection(file)

	_ = c
}
Create and save a Postman Collection
package main

import (
	"os"

	postman "github.com/rbretecher/go-postman-collection"
)

func main() {
    c := postman.CreateCollection("My collection", "My awesome collection")

    c.AddItemGroup("A folder").AddItem(&postman.Item{
        Name:    "This is a request",
        Request: Request{
            URL: &URL{
                Raw: "http://www.google.fr",
            },
            Method: postman.Get,
        },
    })

    file, err := os.Create("postman_collection.json")
    defer file.Close()

    if err != nil {
        panic(err)
    }

    err = c.Write(file)

    if err != nil {
        panic(err)
    }
}
Items

Items are the basic unit for a Postman collection, it can either be a request (Item) or a folder (ItemGroup).

// Create a simple item.
item := postman.CreateItem(postman.Item{
    Name:    "A basic request",
    Request: Request{
        URL: &URL{
            Raw: "http://www.google.fr",
        },
        Method: postman.Get,
    }
})

// Create a simple folder.
folder := postman.CreateItemGroup(postman.ItemGroup{
    Name: "A folder",
})

// Add the item to the folder
folder.AddItem(item)
Request

Part of the Item, a Request represents an HTTP request.

// Basic request
req := Request{
    URL: &URL{
        Raw: "http://www.google.fr",
    },
    Method: postman.Get,
}

// Complex request
req := postman.Request{
    URL: &postman.URL{
        Raw: "http://www.google.fr",
    },
    Method: postman.Post,
    Body: &postman.Body{
        Mode: "raw",
        Raw:  "{\"key\": \"value\"}",
    },
}
Auth

Auth can be added to a Request or an ItemGroup.

// Create basic auth with username and password
auth := postman.CreateAuth(postman.Basic, postman.CreateAuthParam("username", "password"))
Variable

Variable can be added to Collection, Item, ItemGroup and URL.

v := postman.CreateVariable("env", "prod")

Current support

For now, it does not offer support all objects. Feel free to submit a pull request if you want to add support for one of those objects.

 Object v2.0.0 v2.1.0
Collection Yes Yes
ItemGroup (Folder) Yes Yes
Item Yes Yes
Request Yes Yes
Response Yes Yes
Event Yes Yes
Variable Yes Yes
Auth Yes Yes

Documentation

Index

Constants

View Source
const (
	// APIKey stands for API Key Authentication.
	APIKey authType = "apikey"
	// AWSV4 is Amazon AWS Authentication.
	AWSV4 authType = "awsv4"
	// Basic Authentication.
	Basic authType = "basic"
	// Bearer Token Authentication.
	Bearer authType = "bearer"
	// Digest Authentication.
	Digest authType = "digest"
	// Hawk Authentication.
	Hawk authType = "hawk"
	// NoAuth Authentication.
	NoAuth authType = "noauth"
	// OAuth1 Authentication.
	OAuth1 authType = "oauth1"
	// OAuth2 Authentication.
	OAuth2 authType = "oauth2"
	// NTLM Authentication.
	NTLM authType = "ntlm"
)
View Source
const (
	HTML       string = "html"
	Javascript string = "javascript"
	JSON       string = "json"
	Text       string = "text"
	XML        string = "xml"
)

These constants represent the available raw languages.

View Source
const (
	// V210 : v2.1.0
	V210 version = "v2.1.0"
	// V200 : v2.0.0
	V200 version = "v2.0.0"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Auth

type Auth authV210

Auth contains the authentication method used and its associated parameters.

func CreateAuth added in v0.2.0

func CreateAuth(a authType, params ...*AuthParam) *Auth

CreateAuth creates a new Auth struct with the given parameters.

func (Auth) GetParams

func (a Auth) GetParams() []*AuthParam

GetParams returns the parameters related to the authentication method in use.

func (Auth) MarshalJSON added in v0.2.0

func (a Auth) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoding of a Auth. If the version is v2.0.0 it is returned as an object, otherwise as an array (v2.1.0).

func (*Auth) UnmarshalJSON added in v0.2.0

func (a *Auth) UnmarshalJSON(b []byte) (err error)

UnmarshalJSON parses the JSON-encoded data and create an Auth from it. Depending on the Postman Collection version, an auth property can either be an array or an object.

  • v2.1.0 : Array
  • v2.0.0 : Object

type AuthParam

type AuthParam struct {
	Key   string      `json:"key,omitempty"`
	Value interface{} `json:"value,omitempty"`
	Type  string      `json:"type,omitempty"`
}

AuthParam represents an attribute for any authentication method provided by Postman. For example "username" and "password" are set as auth attributes for Basic Authentication method.

func CreateAuthParam added in v0.2.0

func CreateAuthParam(key string, value string) *AuthParam

CreateAuthParam creates a new AuthParam of type string.

type Body

type Body struct {
	Mode       string       `json:"mode"`
	Raw        string       `json:"raw,omitempty"`
	URLEncoded interface{}  `json:"urlencoded,omitempty"`
	FormData   interface{}  `json:"formdata,omitempty"`
	File       interface{}  `json:"file,omitempty"`
	GraphQL    interface{}  `json:"graphql,omitempty"`
	Disabled   bool         `json:"disabled,omitempty"`
	Options    *BodyOptions `json:"options,omitempty"`
}

Body represents the data usually contained in the request body.

type BodyOptions added in v0.3.0

type BodyOptions struct {
	Raw BodyOptionsRaw `json:"raw,omitempty"`
}

BodyOptions holds body options.

type BodyOptionsRaw added in v0.3.0

type BodyOptionsRaw struct {
	Language string `json:"language,omitempty"`
}

BodyOptionsRaw represents the acutal language to use in postman. (See possible options in the cost above)

type Collection

type Collection struct {
	Auth      *Auth       `json:"auth,omitempty"`
	Info      Info        `json:"info"`
	Items     []*Items    `json:"item"`
	Events    []*Event    `json:"event,omitempty"`
	Variables []*Variable `json:"variable,omitempty"`
}

Collection represents a Postman Collection.

func CreateCollection

func CreateCollection(name string, desc string) *Collection

CreateCollection returns a new Collection.

func ParseCollection

func ParseCollection(r io.Reader) (c *Collection, err error)

ParseCollection parses the content of the provided data stream into a Collection object.

func (*Collection) AddItem

func (c *Collection) AddItem(item *Items)

AddItem appends an item (Item or ItemGroup) to the existing items slice.

func (*Collection) AddItemGroup

func (c *Collection) AddItemGroup(name string) (f *Items)

AddItemGroup creates a new ItemGroup and appends it to the existing items slice.

func (*Collection) Write

func (c *Collection) Write(w io.Writer, v version) (err error)

Write encodes the Collection struct in JSON and writes it into the provided io.Writer.

type Cookie struct {
	Domain     string      `json:"domain"`
	Expires    string      `json:"expires,omitempty"`
	MaxAge     string      `json:"maxAge,omitempty"`
	HostOnly   bool        `json:"hostOnly,omitempty"`
	HTTPOnly   bool        `json:"httpOnly,omitempty"`
	Name       string      `json:"name,omitempty"`
	Path       string      `json:"path"`
	Secure     string      `json:"secure,omitempty"`
	Session    bool        `json:"session,omitempty"`
	Value      string      `json:"value,omitempty"`
	Extensions interface{} `json:"extensions,omitempty"`
}

Cookie represents a cookie that follows the Google Chrome format (https://developer.chrome.com/extensions/cookies)

type Description added in v0.5.0

type Description struct {
	Content string `json:"content,omitempty"`
	Type    string `json:"type,omitempty"`
	Version string `json:"version,omitempty"`
}

Description contains collection description.

func (Description) MarshalJSON added in v0.5.0

func (d Description) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoding of a Description. If the Description only has a content, it is returned as a string.

func (*Description) UnmarshalJSON added in v0.5.0

func (d *Description) UnmarshalJSON(b []byte) (err error)

UnmarshalJSON parses the JSON-encoded data and create a Description from it. A Description can be created from an object or a string.

type Event added in v0.7.0

type Event struct {
	ID       string     `json:"id,omitempty"`
	Listen   ListenType `json:"listen,omitempty"`
	Script   *Script    `json:"script,omitempty"`
	Disabled bool       `json:"disabled,omitempty"`
}

An Event defines a script associated with an associated event name.

func CreateEvent added in v0.7.0

func CreateEvent(listenType ListenType, script []string) *Event

CreateEvent creates a new Event of type text/javascript.

type Header struct {
	Key         string `json:"key"`
	Value       string `json:"value"`
	Disabled    bool   `json:"disabled,omitempty"`
	Description string `json:"description,omitempty"`
}

Header represents an HTTP Header.

type HeaderList added in v0.4.0

type HeaderList struct {
	Headers []*Header
}

HeaderList contains a list of headers.

func (HeaderList) MarshalJSON added in v0.4.0

func (hl HeaderList) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoding of a HeaderList.

func (*HeaderList) UnmarshalJSON added in v0.4.0

func (hl *HeaderList) UnmarshalJSON(b []byte) (err error)

UnmarshalJSON parses the JSON-encoded data and create a HeaderList from it. A HeaderList can be created from an array or a string.

type Info

type Info struct {
	Name        string      `json:"name"`
	Description Description `json:"description"`
	Version     string      `json:"version"`
	Schema      string      `json:"schema"`
}

Info stores data about the collection.

type Item

type Item struct {
	Name                    string      `json:"name"`
	Description             string      `json:"description,omitempty"`
	Variables               []*Variable `json:"variable,omitempty"`
	Events                  []*Event    `json:"event,omitempty"`
	ProtocolProfileBehavior interface{} `json:"protocolProfileBehavior,omitempty"`
	ID                      string      `json:"id,omitempty"`
	Request                 *Request    `json:"request,omitempty"`
	Responses               []*Response `json:"response,omitempty"`
}

An Item is an entity which contain an actual HTTP request, and sample responses attached to it.

type ItemGroup

type ItemGroup struct {
	Name                    string      `json:"name"`
	Description             string      `json:"description,omitempty"`
	Variables               []*Variable `json:"variable,omitempty"`
	Events                  []*Event    `json:"event,omitempty"`
	ProtocolProfileBehavior interface{} `json:"protocolProfileBehavior,omitempty"`
	Items                   []*Items    `json:"item"`
	Auth                    *Auth       `json:"auth,omitempty"`
}

A ItemGroup is an ordered set of requests.

type Items

type Items struct {
	// Common fields.
	Name                    string      `json:"name"`
	Description             string      `json:"description,omitempty"`
	Variables               []*Variable `json:"variable,omitempty"`
	Events                  []*Event    `json:"event,omitempty"`
	ProtocolProfileBehavior interface{} `json:"protocolProfileBehavior,omitempty"`
	// Fields specific to Item
	ID        string      `json:"id,omitempty"`
	Request   *Request    `json:"request,omitempty"`
	Responses []*Response `json:"response,omitempty"`
	// Fields specific to ItemGroup
	Items []*Items `json:"item"`
	Auth  *Auth    `json:"auth,omitempty"`
}

Items are the basic unit for a Postman collection. It can either be a request (Item) or a folder (ItemGroup).

func CreateItem added in v0.2.0

func CreateItem(i Item) *Items

CreateItem is a helper to create a new Item.

func CreateItemGroup added in v0.2.0

func CreateItemGroup(ig ItemGroup) *Items

CreateItemGroup is a helper to create a new ItemGroup.

func (*Items) AddItem added in v0.1.1

func (i *Items) AddItem(item *Items)

AddItem appends an item to the existing items slice.

func (*Items) AddItemGroup added in v0.1.1

func (i *Items) AddItemGroup(name string) (f *Items)

AddItemGroup creates a new Item folder and appends it to the existing items slice.

func (Items) IsGroup

func (i Items) IsGroup() bool

IsGroup returns false as an Item is not a group.

func (Items) MarshalJSON added in v0.1.1

func (i Items) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoding of an Item/ItemGroup.

type ListenType added in v0.7.0

type ListenType string

ListenType defines the kind of script attached to an event.

const (
	// PreRequest script is usually executed before the HTTP request is sent.
	PreRequest ListenType = "prerequest"
	// Test script is usually executed after the actual HTTP request is sent, and the response is received.
	Test ListenType = "test"
)

type Method added in v0.6.0

type Method string

Method defines common HTTP methods.

const (
	// Get HTTP Method.
	Get Method = "GET"
	// Put HTTP Method.
	Put Method = "PUT"
	// Post HTTP Method.
	Post Method = "POST"
	// Patch HTTP Method.
	Patch Method = "PATCH"
	// Delete HTTP Method.
	Delete Method = "DELETE"
	// Copy HTTP Method.
	Copy Method = "COPY"
	// Head HTTP Method.
	Head Method = "HEAD"
	// Options HTTP Method.
	Options Method = "OPTIONS"
	// Link HTTP Method.
	Link Method = "LINK"
	// Unlink HTTP Method.
	Unlink Method = "UNLINK"
	// Purge HTTP Method.
	Purge Method = "PURGE"
	// Lock HTTP Method.
	Lock Method = "LOCK"
	// Unlock HTTP Method.
	Unlock Method = "UNLOCK"
	// Propfind HTTP Method.
	Propfind Method = "PROPFIND"
	// View HTTP Method.
	View Method = "VIEW"
)

type QueryParam added in v0.9.0

type QueryParam struct {
	Key         string  `json:"key"`
	Value       string  `json:"value"`
	Description *string `json:"description"`
}

type Request

type Request struct {
	URL         *URL        `json:"url"`
	Auth        *Auth       `json:"auth,omitempty"`
	Proxy       interface{} `json:"proxy,omitempty"`
	Certificate interface{} `json:"certificate,omitempty"`
	Method      Method      `json:"method"`
	Description interface{} `json:"description,omitempty"`
	Header      []*Header   `json:"header,omitempty"`
	Body        *Body       `json:"body,omitempty"`
}

A Request represents an HTTP request.

func (Request) MarshalJSON added in v0.1.1

func (r Request) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoding of a Request. If the Request only contains an URL with the Get HTTP method, it is returned as a string.

func (*Request) UnmarshalJSON added in v0.1.1

func (r *Request) UnmarshalJSON(b []byte) (err error)

UnmarshalJSON parses the JSON-encoded data and create a Request from it. A Request can be created from an object or a string. If a string, the string is assumed to be the request URL and the method is assumed to be 'GET'.

type Response added in v0.4.0

type Response struct {
	ID              string      `json:"id,omitempty"`
	OriginalRequest *Request    `json:"originalRequest,omitempty"`
	ResponseTime    interface{} `json:"responseTime,omitempty"`
	Timings         interface{} `json:"timings,omitempty"`
	Headers         *HeaderList `json:"header,omitempty"`
	Cookies         []*Cookie   `json:"cookie,omitempty"`
	Body            string      `json:"body,omitempty"`
	Status          string      `json:"status,omitempty"`
	Code            int         `json:"code,omitempty"`
	Name            string      `json:"name,omitempty"`
	PreviewLanguage string      `json:"_postman_previewlanguage,omitempty"`
}

A Response represents an HTTP response.

type Script added in v0.7.0

type Script struct {
	ID   string   `json:"id,omitempty"`
	Type string   `json:"type,omitempty"`
	Exec []string `json:"exec,omitempty"`
	Src  *URL     `json:"src,omitempty"`
	Name string   `json:"name,omitempty"`
}

A Script is a snippet of Javascript code that can be used to to perform setup or teardown operations on a particular response.

type URL

type URL struct {
	Raw       string        `json:"raw"`
	Protocol  string        `json:"protocol,omitempty"`
	Host      []string      `json:"host,omitempty"`
	Path      []string      `json:"path,omitempty"`
	Port      string        `json:"port,omitempty"`
	Query     []*QueryParam `json:"query,omitempty"`
	Hash      string        `json:"hash,omitempty"`
	Variables []*Variable   `json:"variable,omitempty" mapstructure:"variable"`
	// contains filtered or unexported fields
}

URL is a struct that contains an URL in a "broken-down way". Raw contains the complete URL.

func (URL) MarshalJSON

func (u URL) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoding of an URL. It encodes the URL as a string if it does not contain any variable. In case it contains any variable, it gets encoded as an object.

func (URL) String

func (u URL) String() string

String returns the raw version of the URL.

func (*URL) UnmarshalJSON added in v0.1.1

func (u *URL) UnmarshalJSON(b []byte) (err error)

UnmarshalJSON parses the JSON-encoded data and create an URL from it. An URL can be created from an object or a string. If a string, the value is assumed to be the Raw attribute of the URL.

type Variable added in v0.1.1

type Variable struct {
	ID          string `json:"id,omitempty"`
	Key         string `json:"key,omitempty"`
	Type        string `json:"type,omitempty"`
	Name        string `json:"name,omitempty"`
	Value       string `json:"value,omitempty"`
	Description string `json:"description,omitempty"`
	System      bool   `json:"system,omitempty"`
	Disabled    bool   `json:"disabled,omitempty"`
}

A Variable allows you to store and reuse values in your requests and scripts.

func CreateVariable added in v0.2.0

func CreateVariable(name string, value string) *Variable

CreateVariable creates a new Variable of type string.

Jump to

Keyboard shortcuts

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