Skip to content

Instantly share code, notes, and snippets.

@rniemeyer
Last active May 6, 2021 18:13
Show Gist options
  • Save rniemeyer/31f6b01cf5ac2dcb20632f7b2ffcaec7 to your computer and use it in GitHub Desktop.
Save rniemeyer/31f6b01cf5ac2dcb20632f7b2ffcaec7 to your computer and use it in GitHub Desktop.
That Conference 2019 - Postman Talk - Ryan Niemeyer

Postman

An Incredible Tool For API Development And Testing

Ryan Niemeyer - @rpniemeyer - Planview / LeanKit

Postman getpostman

Download from here

Free tool is extremely useful. For paid services, check comparison here.

Basic Usage

  • Hit "+" to get a new tab
  • Choose your verb (common are GET, POST, PUT, PATCH, DELETE)
  • Enter URL and Send
  • Can hover over Status and Headers to get more information

More Advanced Usage

  • Authorization - discrete fields for all of the various types. Docs here.
  • Query/Path params - can enter in fields on "Params" tab rather than manipulate URL
  • Body options - Raw is most commmon (application/json). GraphQL is a new beta tab that features auto-complete when using a schema.
  • Code button allows you to generate snippets of code in various languages to make a request. Curl is useful to paste into a terminal.

Workflow for Capturing and Importing a Request

  • Go to Chrome Dev Tools
  • On the Network tab, capture requests
  • Right-click on a request
  • Choose "Copy as cURL"
  • Import into Postman
  • Go to "Paste Raw Text" tab and paste, then Import
  • Now you will have the request and all headers ready to go

Environments

  • Environments are named sets of variables that are typically used to represent different contexts like test server vs. staging server vs. production

Variables

  • Docs here
  • Can dynamically change any value in a request
  • Specify a variable like {{myVariable}}
  • Can get/set in scripts as well

Dynamic variables

  • Docs here
  • Many dynamic variables like {{$guid}}, {{$timestamp}}, {{$randomFirstName}}, {{$randomInt}} and many more

Managing environmentes

  • Use eyeball icon to quickly view/edit current environment and see global variables
  • Hit gear icon (next to eyeball) to manage environments where you can duplicate, export, delete, and edit environments
  • Current value is not sent to Postman servers. For Initial value, you can use things like "YOURPASSWORDHERE" for sensitive data, then can share with others to use same variable structure.

Collections

  • Save requests into Collectons to organize/document or run as a set
  • Can set things like Authorization, scripts, and variables at collection level
  • Can further nest requests into folders for organization
  • Can set Authorization at folder level. For tests, could have folders for Admin, Normal, and Read-Only user workflows, as an example.

Collection Source Control

  • can fork, pull, merge with conflict resolution
  • docs here

Collection Runner

  • Execute a set of requests
  • Can choose environment, # of iterations and other options
  • Results will show executions and test pass/fail

Data Files

  • Can use a CSV or JSON file to run requests with different variables for each variation.
  • In next examples, collection runner with execute 3 iterations with different variable values for each one

CSV

variable1,variable2
foo,bar
apple,banana
ketchup,mustard

JSON

[
    {
        "variable1": "foo",
        "variable2": "bar"
    },
    {
        "variable1": "apple",
        "variable2": "banana"
    },
    {
        "variable1": "ketchup",
        "variable2": "mustard"
    }
]
  • For data files, you would normally have variables to set up request and variables for what you expect in response like (error code, error message, body contents, etc.)

Scripting

  • Postman scripting is written using JavaScript
  • Code is executed in the Postman Sandbox
  • You have access to require a number of common libraries
  • The pm global object provides a number of useful functions like
    • pm.request - access properties of the request
    • pm.response - access properties of response like status code, response time, body, headers
    • pm.test - execute a test
    • pm.expect - assert a value in a test
    • pm.variables - access variables
    • pm.environment - get/set environment variables
    • pm.globals - get/set global variables
    • pm.sendRequest - programmatically send a request

Pre-request Scripts

  • Runs before request
  • Typical used to set a variable
  • Could programmatically make a request and set a variable from response (like get an API token)

Example:

const moment = require( "moment" );
const now = moment();
pm.environment.set("now_formatted", now.format() );
pm.environment.set("now_unix", now.unix() );

Test Scripts

  • Runs after request. Docs here
  • Can test status code, response time, response body, etc.
  • Can set a variable that a subsequent request might need (create a record and save id)
  • Test assertions use Chai assertion library. Syntax help here

A few test examples:

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

pm.test("Response time is less than 500ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(500);
});

pm.test("Body looks correct", function () {
    pm.expect(pm.response.text()).to.include("<title>Knock Me Out</title>");
});

Newman

  • Docs here and repo is here
  • CLI (command-line interface) tool that has feature parity with collection runner
  • Can't always run in UI and want to integrate with build system / automated tests
  • Install like npm install -g newman
  • Run like newman run collection.json -e environment.json --bail
  • Can run against exported files or against those saved to Postman servers

Using Newman as a Node dependency

  • For the ultimate flexibility / control, you can use Newman as a node dependency
  • Not limited to Postman sandbox

Example:

const newman = require( "newman" );

newman.run( {
	collection: require( "./lk-collection.json" ),
	environment: require( "./lk-env" ),
	reporters: "cli"
}, ( err, summary ) => {
	if ( err ) {
		throw err;
	}

	console.log( "Success", summary );
} );
  • Gets a callback with error that can be checked/thrown and summary object that has a ton of information related to the run including results/timings
  • Additionally, there are a number of events that you can attach to like:
const newman = require( "newman" );

newman.run( {
	collection: require( "./lk-collection.json" ),
	environment: require( "./lk-env" ),
	reporters: "cli"
} ).on( "request", ( err, data ) => {
	console.log( data.response.code );
} );

Services

  • Postman offers a number of services and sets limits based on your edition. Compare here

Monitors

  • Monitor a collection.
  • Choose how often and from which region requests are initiated
  • Docs here

Mocks

  • Mock a collection. Provides a URL and does good matching to hit your APIs.
  • Uses saved responses. Can match against saved responses by query params or status code.
  • Can use x-mock-response-code to force mock to return a status code
  • Full docs here

API Documentation

  • Generate documentation from a collection
  • Uses descriptions (can be markdown)
  • Uses body and saved responses from requests
  • Can use a custom URL
  • Docs here
  • Instructions on how to generate a "Run in Postman" button here

Thanks!

I hope that you will be able to get more out of Postman

Postman

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment