Contents
- API
- What is Postman?
- Organizational features in Postman
- Workspaces
- Collections
- Folder
- API requests
- Methods
- Sending parameters
- Sending body data
- Form data
- URL-encoded
- Raw data
- Binary data
- GraphQL
- Understanding API Authorization Options in Postman
- Basic Auth
- API Keys
- OAuth 2
- Configuring request headers
- Use of variables
- Variable scopes
- Choosing variables
- Defining variables
- Defining environment variables
- Defining collection variables
- Defining global variables
- Defining local variables
- Using data variables
- Using dynamic variables
- Accessing variables
- Sharing and persisting data
- Logging variables
- Scripting in Postman
- Execution order of scripts
- Writing pre-request scripts
- Re-using pre-request scripts on collections
- Writing tests
- Writing test scripts
- Testing collections and folders
- Using the Collection Runner
- Scheduling collection runs with monitors
- Building request workflows [Branching and looping]
- Set the request to be executed next
- Loop over the current request
- Stop workflow execution
- Importing and exporting data
- Importing data into Postman
- Importing Postman data
- Importing via Bitbucket repositories
- Exporting Postman data
- Exporting collections
- Exporting environments
- Exporting data dumps
- Importing data into Postman
- Integrating with Postman
- Backing up collections on Bitbucket
- Configuring a Bitbucket integration
- Using version control
- Creating pull requests
- Backing up collections on Bitbucket
API
An API, or Application Programming Interface, is just an interface that defines the ways that scripts or programs can communicate with an application or service.
Testers are used to thinking about the UI when they think about software, but APIs are also interfaces that need testing. Because they are programming interfaces, we do need the help of tools in order to test them effectively.
For API testing we need to specify an endpoint that we want to use. Endpoints define some kind of resource on a server that we want information about. We also need to define an HTTP method. These methods are things like GET, POST, PUT, DELETE, etc. and they tell the server whether we are trying to retrieve information or what kinds of modifications we would like the application to do.
There are many tools that can help with API testing.
What is Postman?
Postman has become the most popular API testing tool, as it is free, packed with powerful testing features, and is also quite intuitive to use and get started with.
API testing is a critical function for most modern web and mobile applications. API testing is becoming a requirement for the internal parts of all applications as well. Even when a UI is available, API tests often execute more quickly, break less frequently, and allow for more flexibility in a microservices environment.
Postman provides you with a number of building blocks that you can use for various kinds of API testing. Click on the New button at the top left-hand side of Postman to see the various building blocks available.
Ex: Request, Collections, workspace, environments, etc..
Organizational features in Postman
Postman offers three tools for organizing requests into a hierarchy:
Workspaces
These are at the root of the organizational hierarchy of postmen. It allows you to organize and collaborate on API projects with your team. Within each workspace, you can share APIs, collections, environments, and other components of your work in Postman.
Collections
Collections are available inside a workspace. They contain a group of saved requests those can be executed, hold variables as well as pre and post-request scripts.
Folder
Folders are available inside the collection. They contain a group of saved requests those can be organized into folders and can also have their own pre/post-request scripts.
API requests
In Postman you can make API requests and examine the responses without using a terminal or writing any code. When you create a request and click Send, the API response appears inside the Postman user interface.
The requests can include multiple details determining the data Postman will send to the API.
We of course will need to enter a URL and choose a method for the request in addition we can optionally specify a variety of other details too. Ex: methods, parameters, body data, header & authentication etc.
Methods
You can use a variety of methods to send data to your APIs, including the following most common options:
GET- get existing data
POST—add new data
PUT—replace existing data
PATCH—update some existing data fields
DELETE—delete existing data
Sending parameters
Query parameters are appended to the end of the request URL, following ? and listed in key value pairs, separated by & using the following syntax: ?id=1&type=new
Path parameters form part of the request URL, and are referenced using placeholders preceded by : as in the following example: /customer/:id
Sending body data
You will need to send body data with requests whenever you need to add or update structured data. You can use variables in your body data and Postman will populate their current values when sending your request.
You can send various different types of body data to suit your API.
Form data
Website forms often send data to APIs as multipart/form-data. Form data allows you to send key-value pairs, and specify the content type.
URL-encoded
URL-encoded data uses the same encoding as URL parameters. If your API requires url-encoded data, select x-www-form-urlencoded in the Body tab & enter your key-value pairs to send with the request and Postman will encode them before sending.
Raw data
You can use raw body data to send anything you can enter as text. Use the raw tab, and the type drop-down list to indicate the format of your data (Text, JavaScript, JSON, HTML, or XML) and Postman will enable syntax-highlighting as well as appending the relevant headers to your request.
Binary data
You can use binary data to send information you can't enter manually in the Postman editor with your request body, such as image, audio, and video files (you can also send text files).
GraphQL
You can send GraphQL queries with your Postman requests by selecting the GraphQL tab in the request Body. Enter your code in the Query area and any variables in the GraphQL Variables section.
Understanding API Authorization Options in Postman
We can test open APIs that don’t require authorization.
Most APIs, however, will require you to authorize them before you can use them. Let’s understand the different methods of API authorization available.
Basic Auth
API Keys
OAuth 2
Basic Auth
With basic auth, you simply need to provide a username and password. In order to use basic auth in Postman, you will of course need an API that supports this type of authentication as well as a username and password that will give you access to the API.
To set up your test, go to the request in Postman that you need to authenticate and click on the Authorization tab. On that tab, there is a Type dropdown where you can select the type of authorization your API uses. Select Basic Auth from there.
You can then fill in your username and password and Postman will take care of the rest for you. If you switch to the Headers tab, you should see an Authorization header that looks something like this:
However, basic auth isn’t used that much anymore in APIs as there are other more secure and convenient ways to authorize API requests.
API Keys
A more common way to do API authorization than basic auth is with an API key. API keys are often preferred because they can be revoked if they are compromised and can be set up to have the precise permissions you want the user to have. In order to use an API key you first need to generate it!
Once you have an API key, you are ready to put it into Postman. In order to do that, you can once again go to the Authorization tab for the API request you want to send. This time choose the Bearer Token option from the Type drop-down. You can then paste your API key into the Token field. If you switch to the Headers tab, you will see something that looks like this:
Note that this time instead of starting with Basic the authorization header starts with Bearer. This lets the API server know that you are using a key for authentication.
OAuth 2
Strictly speaking, OAuth isn’t a way to authenticate, it’s a way to delegate permissions. If you test an API with OAuth, Postman can support you. At the end of the day, authorization with OAuth means you use an access token, much like the API key method. The difference is in how you get that key. Instead of just having it generated for you, you have to follow an OAuth flow in order to generate it.
If you are trying to set this up for an API and you have your key, you can go to the Authorization tab in Postman for the request you are trying to authorize and set the type to OAuth 2.0. From there you can click on the Get New Access Token and fill in the appropriate details as given by the API documentation and you can then click on the Request Token button to get the token that you need.
Configuring request headers
Using a postman we can send particular headers along with requests. You can set these up in the Headers tab. Enter any key-value pairs you need and Postman will send them along with your request.
Tips :
You can save commonly used headers together in a header preset. In the Headers tab, click the Presets drop-down, and choose Manage Presets. Add each preset by providing a name, and entering the key plus value. Click Add and your preset will be available in the Presets drop-down. Selecting the preset will auto-populate the fields in your request headers.
Use of variables
Variables allow you to store and reuse values in your requests and scripts. By storing a value in a variable, you can reference it throughout your collections, environments, and requests—and if you need to update the value, you only have to change it in one place. Using variables increases your ability to work efficiently and minimizes the likelihood of error. Also, it makes your requests more flexible and readable.
Postman supports variables at different scopes, allowing processing to a variety of development, testing, and collaboration tasks. You can use variables to pass data between requests and tests.
Variables in Postman are key-value pairs. Each variable name represents its key, so referencing the variable name allows you to access its value.
Tips :
Postman will store environment and global variables as strings. If you’re storing objects or arrays, remember to JSON.stringify() them before storing, and JSON.parse() them when you retrieve them.
Ex : if you have a base URL for requests stored in a variable named apiUrl, you can reference it in your requests using {{apiUrl}}. Whatever value is stored in the variable will be included wherever you've referenced the variable when your requests run.
Variable scopes
Postman supports the following variable scopes:
Global
Collection
Environment
Data
Local
Note : If a variable with the same name is declared in two different scopes, the value stored in the variable with the narrowest scope will be used—for example if there is a global and a local variable both named username, the local value will be used when the request runs.
Choosing variables
Variable scopes are suited to different tasks in Postman:
Global variables allow you to access data between collections, requests, test scripts, and environments. Global variables are available throughout a workspace.
Collection variables are available throughout the requests in a collection and are independent of environments, so do not change based on the selected environment.
Environment variables You can use environments to group sets of variables together and share them with collaborators. It allow you to tailor your processing to different environments, for example local development vs testing or production. Only one environment can be active at a time.
Local variables are temporary, and only accessible in your request scripts. Local variable values are scoped to a single request or collection run, and are no longer available when the run is complete.
Data variables come from external CSV and JSON files to define data sets you can use when running collections via Newman or the Collection Runner.
Defining variables
You can define variables in a variety of ways, depending on whether you need global, environment or collection scope.
To create a variable at any scope from the request builder, select the data you need, for example in the address, parameters, headers, or body.
Choose Set as variable > Set as a new variable.
Enter a Name, verify the Value and select a scope from the drop-down list. Click Set variable.
Defining environment variables
You can create and edit environment variables by selecting Environments on the left of Postman, or using the Environment quick look at the top right.
In the environment quick look, you will see the selected environment along with global variables in your workspace. You can edit the current value for an existing variable inline, by clicking the value. To add a variable, click Edit next to the environment or global section.
Use pm.environment to define an environment variable (in the currently selected environment), You can use unset to remove a variable:
pm.environment.set("variable_key", "variable_value");
pm.environment.get("variable_key");
pm.environment.unset("variable_key");
Defining collection variables
You can add collection variables when you create the collection or at any time after that. To create or edit a variable for an existing collection, select the collection in the Collections sidebar on the left of Postman and choose Variables.
Use pm.collectionVariables to define/get a collection variable programmatically in your request scripts.
pm.collectionVariables.set("variable_key", "variable_value");
pm.collectionVariables.get("variable_key");
Defining global variables
Use pm.globals to define/get a global variable programmatically in your request scripts.
pm.globals.set("variable_key", "variable_value");
pm.globals.get("variable_key");
Defining local variables
Local variables are temporary values you set in your request scripts using the following syntax:
Use pm.variables to define/get a local variable programmatically in your request scripts.
pm.variables.set("variable_key", "variable_value");
pm.variables.get("variable_key");
Local variables do not persist between sessions but allow you to override all other scopes temporarily, during the execution of a request or collection/monitor run.
Using data variables
The Collection Runner lets you import a CSV or a JSON file, and use the values from the data file inside requests and scripts. You cannot set a data variable inside Postman because it is pulled from the data file, but you can access data variables inside scripts, for example using pm.iterationData.get("variable_name").
Using dynamic variables
Postman provides dynamic variables that you can use in your requests.
Examples of dynamic variables are as follows:
{{$guid}} : A v4 style guid
{{$timestamp}}: The current timestamp (Unix timestamp in seconds)
{{$randomInt}}: A random integer between 0 and 1000
To use dynamic variables in pre-request or test scripts, you need to use
pm.variables.replaceIn(), e.g. pm.variables.replaceIn('{{$randomFirstName}}').
Accessing variables
You can use double curly braces to reference variables throughout the Postman user interface. For example, to reference a variable named "username" in your request auth settings, you could use the following syntax with double curly braces around the name: {{username}}
When you run a request, Postman will resolve the variable and replace it with its current value.
You can use variables in request URLs, parameters, headers, authorization, body, and header presets.
When you hover over a variable you can see an overview of its current status. As you type variables into your requests, Postman will prompt you with any that are currently defined.
The prompt will indicate current value, scope (highlighted by color), and overridden status where relevant.
If a variable is unresolved, Postman will highlight it in red.
Sharing and persisting data
When you edit global, collection, and environment variables in Postman, you will see Current Value, Persist, and Reset options for individual variables and for all variables.
These allow you to control what happens within your local instance of Postman, independently of how the data is synced with anyone sharing your workspace, requests, collections, and environments.
Your local session in Postman can use values that are transient and only visible to you. This lets you develop and test using private credentials or experimental values, without risk of exposing these details or affecting others on your team.
When you create or edit a variable, you can enter both an initial and a current value. When you create a new variable in the UI, if you leave the current value empty, it will auto-fill with the initial value. If you specify a current value, it will be local only to your instance—the Persist option lets you push your current value to the shared data, updating the initial value to match the current value.
Using Persist will make your current value sync with Postman's servers and be reflected for anyone sharing your collection or environment. To reset your current local values to reflect the initial (shared) values, use Reset.
You can edit a current value inline from the environment quick look:
Local and data variables only have current values, which do not persist beyond request or collection runs.
Logging variables
You can log variable values to the Postman Console while your requests run. Open the console from the button on the bottom left of Postman, or from the View menu. To log the value of a variable, use the following syntax in your script:
console.log(pm.variables.get("variable_key"));
Scripting in Postman
Postman allows you to write test suites, build requests that can contain dynamic parameters, pass data between requests, and a lot more. You can add JavaScript code to execute during 2 events in the flow:
Before a request is sent to the server, as a pre-request script under the Pre-request Script tab.
After a response is received, as a test script under the Tests tab.
Postman will prompt you with suggestions as you type—select one to autocomplete your code.
You can add pre-request and test scripts to a collection, a folder, a request within a collection, or a request not saved to a collection.
Execution order of scripts
In Postman, the script execution order for a single request looks like this:
A pre-request script associated with a request will execute before the request is sent
A test script associated with a request will execute after the request is sent
For every request in a collection, scripts will execute in the following order:
A pre-request script associated with a collection will run prior to every request in the collection.
A pre-request script associated with a folder will run prior to every request in the folder.
A test script associated with a collection will run after every request in the collection.
A test script associated with a folder will run after request in the folder.
If you created log statements in the pre-request and test script sections for the collection, folder, and requests, you would clearly see the execution order in the Postman console.
Writing pre-request scripts
You can use pre-request scripts in Postman to execute JavaScript before a request runs. By including code in the Pre-request Script tab for a request, collection, or folder, you can carry out pre-processing such as setting variable values, parameters, headers, and body data. You can also use pre-request scripts for debugging code, for example by logging output to the console.
Example usage of pre-request scripting could be as follows:
You have a series of requests in a collection and are running them in a sequence, e.g. using the collection runner.
The second request is dependent on a value returned from the first request.
The value needs to be processed before you pass it to the second request.
The first request sets the data value from a response field to a variable in its Tests script.
The second request retrieves the value and processes it in its Pre-request Script, then sets the processed value to a variable (which is referenced in the second request, e.g. in its parameters).
Re-using pre-request scripts on collections
You can add pre-request scripts to entire collections as well as to folders within collections. In both cases, your pre-request script will run before every request in the collection or folder. This allows you to define commonly used pre-processing or debugging steps you need to execute for multiple requests.
Writing tests
You can write test scripts for your Postman API requests in JavaScript. Tests allow you to ensure that your API is working as expected. You can also use test code to aid the debugging process when something goes wrong with your API project.
You can add tests to individual requests, folders, and collections. Postman includes code snippets you can click to add, then amend to suit your logic if necessary.
To add tests to a request, open the request and enter your code in the Tests tab. Tests will execute after the request runs. You will be able to see the output in the Test Results tab alongside the response data.
Writing test scripts
Your test scripts can use dynamic variables, carry out test assertions on response data, and pass data between requests. In the Tests tab for a request, you can enter your JavaScript manually or use the Snippets you'll see to the right of the code editor.
Tests will execute after the response is received, so when you click Send, Postman will run your test script when the response data returns from the API.
To carry out tests in order to validate the data returned by a request, you can use the pm.response object. You can define tests using the pm.test function, providing a name and function that returns a boolean (true or false) value For example, enter the following in the Tests tab for any request to test whether the response status code is 200.
pm.test("Status test", function () {
pm.response.to.have.status(200);
});
The tab header displays how many tests passed and how many ran in total. You can also toggle between passed, skipped, and failed test results.
If the request returned a 200 status code, the test will pass—otherwise it will fail. Try changing the expected status code in your test script and running the request again.
Using the pm.expect syntax gives your test result messages a different format.
Your code can test the request environment, as in the following example:
pm.test("environment to be production", function () {
pm.expect(pm.environment.get("env")).to.equal("production");
});
If you share a collection or publish documentation / the Run in Postman button, your test code will be included for anyone who views or imports your templates.
Testing collections and folders
You can add test scripts to a collection, a folder, or a single request within a collection. A test script associated with a collection will run after every request in the collection. A test script associated with a folder will run after every request in the folder. This allows you to reuse commonly executed tests after every request.
When you run a collection you will see the test results output by the collection runner.
Using the Collection Runner
The Collection Runner allows you to run sets of requests in a specified sequence. The Collection Runner will log your request test results, and your scripts can pass data between requests as well as altering the request workflow.
You can run collections against specific environments and can pass data files into a run. Collection runs allow you to automate your API testing, and you can schedule runs using monitors. You can integrate collection runs to your CI/CD pipeline using Postman's CLI Newman.
To run a collection, open a collection and click Run on the overview tab.
You can also click Runner at the bottom right of Postman and drag a collection over from Collections or History on the left.
By default your requests will run in the sequence they are listed in the collection, but you can click to the left of each one and drag to move it if you need to change the order of execution. You can also deselect an individual request by unchecking its box.
If you want your collection to run against an environment, make the environment active by selecting it from the drop-down list at the top right of Postman, or from Environments on the left.
You can optionally choose config parameters for your collection run:
The number of iterations for your collection run. You can also run collections multiple times against different data sets to build workflows.
An interval delay (milliseconds) between each request.
A data file for the collection run.
Saving responses to the log will allow you to review them but can affect performance.
Persisting variables will mean that any variables updated by the run will remain changed after it. If you do not persist variables, changes will not be saved after the run completes. Note that persisting variables in the collection run will update the current value only.
If your requests use cookies, you can optionally disable them for a collection run.
Saving cookies means that any values affected by requests during the run will remain after it completes.
Postman will display your request executions and test results in realtime. To the right, you will see a number for each iteration—click to select one. You will see an overview for each request, including its passed or failed tests—you can filter on each using the Passed and Failed tabs at the top.
If any tests in a request script fail during the collection run, it will be listed as failed—it will be listed as passed if all tests inside it pass.
For additional details such as viewing log statements, open the Console from the bottom left of Postman.
You can export test results and view the Run Summary using the buttons at the top right.
The summary also lists a column for each iteration of your collection run so that you can see test output for the whole run at a glance.
Scheduling collection runs with monitors
In addition to using the Collection Runner in Postman, you can use collection runs in conjunction with other utilities in order to build automation into your API projects.
The Postman command-line interface Newman enables you to run collections and build them into your development pipeline, responding to test outcomes to maintain your API performance.
Adding a monitor to your collection lets you schedule collection runs and stay informed of any issues.
Ex : newman run https://www.getpostman.com/collections/ae157cc4d20e000b09be -e ~/Public/LocalhostEnv.postman_environment.json
You can automate collection runs using monitors to schedule runs and receive reports on your request test results.
To add or access monitors for a particular collection, select the Monitors tab in the left sidebar of Postman.
Any monitors already attached to your collection will appear. Click Create a monitor to add one (or + Create a new Monitor if you already have one on the collection). You can also add a monitor via a collection. To add a monitor via collection, go to the collection, click ... and select Monitor Collection.
Give your monitor a name, select a collection to use, choose a version tag, and an optional environment your scheduled collection runs should reference. Enter the frequency you want your monitor to run on, and select a region. Click Create and your monitor will run on the schedule you entered.
Your new monitor will appear in the monitor overview. You can open the monitor overview tab to view your monitor results at any time.
Building request workflows [Branching and looping]
When you start a collection run, all requests are run in the order you see them in Postman.
However, you can override this behavior using a built-in function called postman.setNextRequest(). This function, as the name suggests, allows you to specify which request runs next.
Set the request to be executed next
postman.setNextRequest("request_name");
console.log(pm.info.requestId); console.log(pm.info.requestName);
Loop over the current request
Providing the name of the current run to setNextRequest leads to Postman running the current request continuously.
TIPs: While looping over one request continuously, one should wrap setNextRequest in some logic so as to ensure that the request does not run indefinitely otherwise the collection runner would need to be force closed.
Stop workflow execution
postman.setNextRequest(null);
Importing and exporting data
Postman can import and export Postman data, including collections, environments, data dumps, and globals. Postman can also import non-Postman data in the form of API schemas to help you consolidate your API development workflow.
Importing data into Postman
You can import collections or your API specifications directly into Postman.
To import your data into Postman, click Import in the upper-left corner.
Importing Postman data
You can import Postman data you previously exported, including collections, environments, data dumps, and globals data from files, folders, links, raw text, or Bitbucket repositories.
Postman will automatically recognize Postman data, confirming the name, format, and what the file will import as. Click Import to bring your data into Postman.
Importing via Bitbucket repositories
You can import data in bulk from a Bitbucket repository by selecting Import > Code repository > Connect to Bitbucket.
Confirm your Bitbucket account and Authorize postman to access your repositories.
In Postman, select your Bitbucket organization, repository, and branch, then Continue.
Confirm the files you would like to import into Postman. You can also opt to Generate a collection from imported APIs and select what you would like to link this collection as. Click Show advanced settings to control how Postman should generate collections based on your file types, then select Import.
You will receive a confirmation once the import has been completed.
You can now view your newly imported files and generated collections in Postman.
Exporting Postman data
You can export your Postman data, including collections, environments, data dumps, and globals, as JSON files. These files can be imported back into any Postman instance.
Exporting collections
You can export your collections from Postman by selecting the ... next to the collection, then Export.
You can then select the format you'd like your collection to export as. Click Export to download your newly generated JSON file.
The export to Collection v1 format is no longer supported in Postman.
Exporting environments
You can export your environments from Postman by selecting the gear icon in the upper-right corner to open Manage Environments. Click the download symbol next to your environment to download your newly generated JSON file.
Exporting data dumps
You can export a data dump of all of your collections, environments, globals, and header presets in Postman. Select the gear icon in the upper-right corner to open Settings. Click to open the Data tab, then Download to save the newly generated JSON file of your Postman data.
Integrating with Postman
Backing up collections on Bitbucket
You can back up your Postman Collections to your Bitbucket repository. Once the integration is configured, any new changes to your collection in Postman will also appear in Bitbucket.
Configuring a Bitbucket integration
To add a Bitbucket integration, navigate to the Postman Integrations page. Search for Bitbucket and select it from the results.
Select Add Integration.
Enter your Bitbucket authentication and select Authenticate and Proceed.
App passwords are different from account passwords. Learn how to create an app password in Bitbucket.
Select your collection to back up, the repository you'd like to back it up to, and designate the directory, filename, and branch. Click Add Integration.
Your new integration will now appear in a list along with previously created integrations.
To confirm this integration, navigate to your Bitbucket dashboard > Repositories. Select your repository > Commits.
You can select a commit to view your stored collection in JSON format.
Using version control
You can use version control with your Postman Collections by forking and merging and utilizing a standard pull request process. Version control allows you to collaborate with teammates by working on different forks of the same collection, updating forks from the parent collection, and merging changes when you're ready. You can tag collaborators to review pull requests and resolve conflicts to manage collection versions.
Postman API Platform | plans & pricing
Version control overview | Postman Learning Center
Creating pull requests
You can merge changes from a collection fork (the source) into the parent (the destination) using a pull request process, by tagging reviewers who can comment on your changes and decide to merge them. In Postman, open the menu for a collection and select Create Pull Request.
Pull request settings are available on Postman Business and Enterprise plans in the Manage Roles section of a collection.
Thanks!
No comments:
Post a Comment