Go module to work with Postman Collections

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 for Response and Event 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 No No
Event No No
Variable Yes Yes
Auth Yes Yes
Owner
Romain Bretécher
Fullstack developer
Romain Bretécher
Comments
  • Support postman options language and remove createRequest calls.

    Support postman options language and remove createRequest calls.

    Add raw options to support JSON/Text etc on postman Removed the CreateRequest cuz it not needed. In the original implementation, the host + method never used and since we can be declared the struct we don't need a function for it.

  • Chrisnesbit1/add event support at the collection level

    Chrisnesbit1/add event support at the collection level

    This PR resolves #11.

    It includes the following changes:

    add Event to postman collections (at the collection level, not individual Items) unit tests add documentation for events to the README

  • Add a QueryFragment struct to be used by URL.Query

    Add a QueryFragment struct to be used by URL.Query

    This PR adds support for the Query objects which are listed in this format:

    "query": [
        {
            "key": "category",
            "value": "todo",
            "description": "..."
        },
    ]
    
  • Allow collection global auth to become null if not defined.

    Allow collection global auth to become null if not defined.

    With the current version of this module it is not possible to publish the generated collections via the Postman API as described here: https://www.postman.com/postman/workspace/postman-public-workspace/documentation/12959542-c8142d51-e97c-46b6-bd77-52bb66712c9a if the collection does not contain a global auth property.

    This leads to a collection with the structure of

    {
        "auth": {},
        "info": {
            "name": "...",
            "description": "...",
            "version": "",
            "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
        },
        "item": []
    }
    

    which causes an error like this:

    failed with status 400: map[error:map[details:[auth: must be null auth: must have required property 'type' auth: must match exactly one schema in oneOf] message:Found 3 errors with the supplied collection. name:malformedRequestError]]

    So the API is expecting only an auth property if it is defined, meaning that the following payload is valid:

    {
        "info": {
            "name": "...",
            "description": "...",
            "version": "",
            "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
        },
        "item": []
    }
    

    Hence, the fix provided in this PR is making the auth property nullable in case that it is not defined.

    Tested it with the API and the manual import via UI and proofed it to be working.

  • Q: Does this library support to make API call thru Golang instead of Postman?

    Q: Does this library support to make API call thru Golang instead of Postman?

    Are you planning to read the collection and do the API requests thru Golang - so that collection json file is been reused if we want to ignore the postman binary for any projects.

    In other words, during development would like to use Postman for testing & debugging, but then would like to re-use the collection json file to be embedded with golang and make API calls thru this library.

  • Collection Auth and Item Responses

    Collection Auth and Item Responses

    This adds collection level auth and item responses.

    Based on the 2.0 spec at https://schema.getpostman.com/collection/json/v2.0.0/draft-04/collection.json we can see:

    • .properties.auth which represents collection wide auth that all items inherit if not set
    • .definitions.item.properties.response which is an array of response types

    This adds Collection.Auth, Item.Responses and Items.Responses and a new concrete Response type.

  • Converting to HTTP requests

    Converting to HTTP requests

    I am curious if there is a method or example of reading a postman collection and turning all of the calls into HTTP requests. This would include auth and variables as well. Or is this something that we need to piece together manually? Thank you!

  • Export method type

    Export method type

    I've tried to generate "dynamic" postman collection, based on handler functions that my app serves. That way, collection generated always synced with handler functions. But i've hard times when dealing with "method" type of this lib, since it's unexported type.

    This is part of my code:

    functions.go

    type FunctionCategory struct {
    	Name      string
    	Functions []*Function
    }
    
    type Function struct {
    	Name        string
    	Description string
    	HandlerFunc http.HandlerFunc
    	Endpoint    string
    	Method      string // i can't use "method" type here, since it's unexported
    }
    
    func AllFunctions() []*FunctionCategory {
    	return []*FunctionCategory{
    		{
    			Name: "FooCategory",
    			Functions: []*Function{
    				{
    					Name:        "Foo API",
    					Description: "Create some bar",
    					HandlerFunc: FooHandlerFunc,
    					Endpoint:    FooEndpoint,
    					Method:      http.MethodPost, // i can't use "Post" from this lib, since it's different typ
    					Request:     FooRequest,
    				},
    			},
    		},
    	}
    }
    

    collection.go

    func CreateCollection() *postman.Collection {
    	functions := handler.AllFunctions(db)
    
    	for _, fc := range functions {
    		items := new(postman.Items)
    		items.Name = fc.Name
    		items.Items = make([]*postman.Items, 0)
    		for _, f := range fc.Functions {
    			item := &postman.Items{
    				Name:        f.Name,
    				Description: f.Description,
    				Request: &postman.Request{
    					URL: &postman.URL{
    						Host: []string{conf.Server.MainURL},
    						Path: []string{f.Endpoint},
    					},
    					Method:      postman.Post, // This will generate compile error, since it's different type
    				},
    			}
    			items.Items = append(items.Items, item)
    		}
    	}
    
    	return c
    }
    

    It's there any specific reason why this type unexported?

  • v0.4.0 : Upgrade Go mod to 1.16, add support for Response/Cookie/Header and add Auth into Collection

    v0.4.0 : Upgrade Go mod to 1.16, add support for Response/Cookie/Header and add Auth into Collection

    This PR adds new features :

    • Upgrade Go mod to 1.16
    • Add Response/Cookie/Header/HeaderList structs
    • Add Auth struct in Collection struct

    Breaking changes:

    • Rename :
      • Items.Response -> Items.Reponses
      • Item.Response -> Item.Responses
  • Support Description Objects

    Support Description Objects

    The Postman Collection spec describes the description object as being an object or a string.

    A Description can be a raw text, or be an object, which holds the description along with its format.

    https://schema.postman.com/collection/json/v2.1.0/draft-04/collection.json

    Currently, only string is supported.

    The goal is to support the description object which enables setting a MIME type (either text/markdown or text/plain) and version.

    {
      "description":{
        "$schema":"http://json-schema.org/draft-04/schema#",
        "id":"#/definitions/description",
        "description":"A Description can be a raw text, or be an object, which holds the description along with its format.",
        "oneOf":[
          {
            "type":"object",
            "title":"Description",
            "properties":{
              "content":{
                "type":"string",
                "description":"The content of the description goes here, as a raw string."
              },
              "type":{
                "type":"string",
                "description":"Holds the mime type of the raw description content. E.g: 'text/markdown' or 'text/html'.\nThe type is used to correctly render the description when generating documentation, or in the Postman app."
              },
              "version":{
                "description":"Description can have versions associated with it, which should be put in this property."
              }
            }
          },
          {
            "type":"string"
          },
          {
            "type":"null"
          }
        ]
      }
    }
    
  • Chrisnesbit1/add event support at the collection level (#1)

    Chrisnesbit1/add event support at the collection level (#1)

    This PR resolves https://github.com/rbretecher/go-postman-collection/issues/11.

    It includes the following changes:

    • add Event to postman collections (at the collection level, not individual Items)
    • unit tests
    • add documentation for events to the README
Go library for interacting with the Discord API (work-in-progress)

zombiezen Go Client for Discord zombiezen.com/go/discord is a WIP Go library for interacting with the Discord API. It differs from DiscordGo by provid

Nov 9, 2022
A work-in-progress implementation of MobileMe.

mobileme A work-in-progress implementation of MobileMe. At the moment, authentication is assumed to be with the username someuser and password testing

May 28, 2022
Go package to work with temperatures

tempconv This is an exercise of the book The Go Programming Language, by Alan A.

Dec 18, 2021
MovieWorkNow - a social network for film work made in go

Movie Work Now Movie Work Now é uma rede social para trabalho relativo a área de

Jan 11, 2022
Go module for communicating with the Veryfi OCR API
Go module for communicating with the Veryfi OCR API

veryfi-go is a Go module for communicating with the Veryfi OCR API Installing This package can be installed by cloning this directory: git clone https

Jan 5, 2023
Golang module for working with VK API

VK SDK for Golang VK SDK for Golang ready implementation of the main VK API functions for Go. Russian documentation Features Version API 5.131. API 40

Dec 10, 2022
This program performs stress testing for the Cosmos module

Cosmos Modules Testing Program ?? Overview This program performs stress testing for the Cosmos module. Support: Liquidity , IBC transfer Note: Require

May 25, 2022
A Lambda function built with SAM (Serverless Application Module)

AWS SAM Lambda Function © Israel Pereira Tavares da Silva The AWS Serverless Application Model (SAM) is an open-source framework for building serverle

Dec 19, 2021
Golang ergonomic declarative generics module inspired by Rust, including Result, Option, and more.

gust Golang ergonomic declarative generics module inspired by Rust. Go Version go≥1.18 Features Result Avoid if err != nil, handle result with chain m

Jan 7, 2023
A Golang REST API to handle users and posts for a simple instagram backend. Uses MongoDB as the database. Tested using golang-testing and Postman.
A Golang REST API to handle users and posts for a simple instagram backend. Uses MongoDB as the database. Tested using golang-testing and Postman.

A Golang REST API to handle users and posts for a simple instagram backend. Uses MongoDB as the database. Tested using golang-testing and Postman.

Oct 10, 2021
Minutes is a CLI tool for synchronizing work logs between multiple time trackers, invoicing, and bookkeeping software to make entrepreneurs' daily work easier.
Minutes is a CLI tool for synchronizing work logs between multiple time trackers, invoicing, and bookkeeping software to make entrepreneurs' daily work easier.

Minutes is a CLI tool for synchronizing work logs between multiple time trackers, invoicing, and bookkeeping software to make entrepreneurs' daily work easier.

Aug 8, 2022
Go collections

collections Summary Basic data structures represent a great opportunity to learn a new langauge. These are some of the data structures that I have bui

Jul 2, 2022
Type-agnostic partitioning for Go's indexable collections and strings.

Go Type-Agnostic Collection Partitioning Type-agnostic partitioning for anything that can be indexed in Go - slices, arrays,strings. Inspired by Guava

Aug 11, 2021
parody of some of the basic python core features (collections package)

collections import "github.com/marcsantiago/collections" Overview Index Subdirectories Overview Index func StringEncoder(encoder *bytes.Buffer, data D

Jan 14, 2022
concurrent caching proxy and decoder library for collections of PMTiles

go-pmtiles A caching proxy for the serverless PMTiles archive format. Resolves several of the limitations of PMTiles by running a minimalistic, single

Jan 2, 2023
A Go Template Library. A bunch of utils and collections that are not part of the Golang standard library.

gotl A Go Template Library. A bunch of utils and collections that are not part of the Golang standard library. Prerequisites This library is using ext

Dec 15, 2021
Utilities and immutable collections for functional programming in Golang

Utilities and immutable collections for functional programming in Golang. This is an experimental library to play with the new Generics Feature in Go 1.18.

Sep 1, 2022
Collections for Golang using generics. Currently containing Hash Set.
Collections for Golang using generics. Currently containing Hash Set.

Implementation of missing colections for Golang using Generics. Free of dependencies. Curently in early development phase. Requirements Go 1.18+ Insta

Dec 30, 2021
🌕 Server application for storing doujinshi, manga, art collections and other galleries with API and user control. Written in Go.

?? Server application for storing doujinshi, manga, art collections and other galleries with API and user control. Written in Go.

Dec 31, 2022