Skip to main content

Running Magento 2 API tests via Postman

This blog post might be outdated!
This blog post was published more than one year ago and might be outdated!
· 2 min read
Stephan Hochdörfer
Head of IT Business Operations

In a current Magento 2 project we are focussing on building a headless instance that communicates with a kind of PWA application. In such an environment testing the APIs via Postman makes sense and since the Magento 2 API is documented via Swagger, one can easily import the API definition into Postman. Here is how to do it with httpie:

If you haven't installed httpie either install it via your system's package manager or via pip:

pip install --upgrade httpie

First of all, we need to get an admin token from Magento 2 by firing the command below against the Magento 2 backend:

http POST http://m2.loc/index.php/rest/V1/integration/admin/token username=admin password=admin123

The response of the command above contains the session token that we need to send as Bearer token when requesting the swagger schema:

http --print=b POST http://m2.loc/index.php/rest/default/schema Authorization:"Bearer 6spm5t6dhsljkhgv4wrjmt05eys2v1ot" > magento2.api.schema.json

Simply import the magento2.api.schema.json file into Postman and you should be able to see all possible API calls.

In case you want to automatically run API tests against the Magento 2 API, you can use newman a command-line collection runner for Postman. Install newman via npm like this:

npm install -g newman

Create a collection of API tests in Postman and export the collection. To run the collection use the following command:

newman run m2_collection.json

As output you will get an overview like this:

┌─────────────────────────┬──────────┬──────────┐
│ │ executed │ failed │
├─────────────────────────┼──────────┼──────────┤
│ iterations │ 1 │ 0 │
├─────────────────────────┼──────────┼──────────┤
│ requests │ 2 │ 0 │
├─────────────────────────┼──────────┼──────────┤
│ test-scripts │ 0 │ 0 │
├─────────────────────────┼──────────┼──────────┤
│ prerequest-scripts │ 0 │ 0 │
├─────────────────────────┼──────────┼──────────┤
│ assertions │ 0 │ 0 │
├─────────────────────────┴──────────┴──────────┤
│ total run duration: 245ms │
├───────────────────────────────────────────────┤
│ total data received: 1.7KB (approx) │
├───────────────────────────────────────────────┤
│ average response time: 87ms │
└───────────────────────────────────────────────┘

For a more in-depth overview on what you can do with newman, check out the newman documentation.