Welcome to your ultimate resource for mastering Postman API Testing! Whether you’re a beginner diving into the world of API testing or an experienced developer looking to enhance your skills, this guide is tailored to provide you with a clear, concise, and comprehensive understanding of Postman and its powerful features. Let’s embark on this journey to transform you into an API testing pro!
Table of Contents
- 1. Introduction to Postman API Testing
- 2. Setting Up Postman for API Testing
- 3. Understanding Postman Test Structure
- 4. Validating Response Bodies
- 5. JSON Schema Validation
- 6. Automating API Tests with Collection Runner
- 7. Scheduling Automated Runs
- 8. Utilizing Postman CLI for Automation
- 9. Integrating Postman Tests with CI/CD
- 10. Collaborating in Postman Workspaces
- 11. Assignments and Hands-On Practice
- 12. Conclusion and Next Steps
1. Introduction to Postman API Testing
Postman is a widely-used tool for developing, testing, and managing APIs. It provides a user-friendly interface to send HTTP requests, inspect responses, and automate tests, making API development and testing more efficient and effective.
Why API Testing?
APIs are the backbone of modern applications, enabling different software components to communicate seamlessly. Ensuring the reliability, performance, and security of APIs is crucial for delivering robust applications. API testing helps in:
- Validating functionality: Ensuring APIs work as intended.
- Ensuring performance: Checking API responsiveness under various conditions.
- Enhancing security: Identifying and mitigating vulnerabilities.
- Maintaining reliability: Ensuring consistent performance over time.
Postman simplifies these testing processes, allowing developers to focus on creating high-quality APIs.
2. Setting Up Postman for API Testing
Before diving into API testing with Postman, it’s essential to set up the environment correctly. This section will guide you through installing Postman, creating and managing collections, and handling environment variables.
• Installing Postman
Step 1: Download Postman
Visit the Postman website and download the appropriate version for your operating system (Windows, macOS, or Linux).
Step 2: Install Postman
- Windows: Run the downloaded
.exe
file and follow the installation prompts. - macOS: Open the downloaded
.dmg
file and drag Postman to the Applications folder. - Linux: Follow the instructions specific to your distribution.
Step 3: Launch Postman
Once installed, launch Postman and sign in or create a free account to sync your collections and settings across devices.
• Creating and Forking Collections
Collections in Postman are groups of related API requests organized in a structured manner. They facilitate easy management, sharing, and automation of API tests.
Creating a Collection
- Open Postman and click on the “New” button in the top-left corner.
- Select “Collection”.
- Name your collection (e.g., “My API Tests”) and add a description if desired.
- Click “Create”.
Forking a Collection
- Navigate to the Collection you want to fork.
- Click on the ellipsis (…) next to the collection name.
- Select “Fork Collection”.
- Name your fork and choose the workspace where it should reside.
- Click “Fork Collection”.
Forking is especially useful for collaborating on shared collections without altering the master version.
• Managing Environment Variables
Environment Variables in Postman store values that can be reused across requests, such as API keys, URLs, and other dynamic data. They enhance flexibility and security in your tests.
Creating an Environment
- Click on the “Environments” dropdown in the top-right corner.
- Select “Manage Environments”.
- Click “Add” to create a new environment.
- Name your environment (e.g., “Development”, “Production”).
- Add variables by specifying the Variable Name and Initial Value (and optionally, the Current Value).
Variable Name Initial Value Current Value baseUrl https://api.example.com
https://api-dev.example.com
apiKey YOUR_API_KEY_HERE
YOUR_API_KEY_HERE
- Click “Save”.
Using Environment Variables in Requests
- Refer to variables using
{{variableName}}
. - Example:
{{baseUrl}}/users/{{userId}}
Environment variables ensure that your tests are adaptable across different setups without hardcoding values.
3. Understanding Postman Test Structure
Testing is integral to API development, ensuring that each endpoint behaves as expected. Postman provides a robust testing framework using JavaScript-based scripts.
• Writing Basic Tests
In Postman, tests are scripts written in JavaScript that run after a request completes. They validate responses, check data integrity, and ensure API reliability.
Creating a Test
- Select a Request within your collection.
- Navigate to the “Tests” tab.
- Write your test script in the editor.
Basic Test Structure
pm.test("Test Name", function () {
// Assertions go here
});
Example: Testing Status Code
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
Explanation:
pm.test
: Defines a test with a descriptive name.pm.response.to.have.status(200)
: Asserts that the response status code is200
.
• Assertions in Postman
Assertions are conditions that must hold true for the test to pass. They validate various aspects of the response, such as status codes, headers, body content, and more.
Common Assertions:
- Status Code:
pm.response.to.have.status(200);
- Response Time:
pm.expect(pm.response.responseTime).to.be.below(200);
- Response Headers:
pm.response.to.have.header("Content-Type");
- Response Body:
pm.expect(pm.response.json()).to.have.property("id");
Chai Assertion Library
Postman utilizes the Chai assertion library, enabling readable and expressive assertions.
Example: Checking a Property Value
pm.test("User ID is correct", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.id).to.eql(12345);
});
Explanation:
pm.response.json()
: Parses the response body as JSON.pm.expect(jsonData.id).to.eql(12345)
: Asserts that theid
property equals12345
.
• Example: Testing Status Codes
Let’s walk through an example to solidify your understanding.
Scenario:
You have an endpoint GET https://api.example.com/status
that should return a status code of 200
when the API is operational.
Creating the Request:
- Create a new request in your collection named “Get API Status”.
- Set the HTTP method to
GET
. - Enter the URL:
https://api.example.com/status
. - Click “Save”.
Writing the Test:
Navigate to the “Tests” tab and add the following script:
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
Explanation:
This test verifies that the API returns a 200 OK
status code, indicating successful operation.
Running the Test:
- Click “Send” to execute the request.
- Navigate to the “Test Results” section to see the outcome.
- If the status code is
200
, the test passes. - Otherwise, it fails, indicating an issue with the API.
- If the status code is
4. Validating Response Bodies
Ensuring that the API returns the correct data structure and content is vital. Postman allows you to perform various validations on the response body to guarantee data integrity.
• Asserting JSON Responses
When dealing with JSON APIs, it’s common to validate the structure and content of the JSON response.
Parsing JSON Response
var jsonData = pm.response.json();
Explanation:
pm.response.json()
: Parses the response body as JSON, allowing you to interact with its properties.
• Data-Type Assertions
Validating the data types of response properties ensures consistency and prevents type-related errors.
Example: Checking Data Types
pm.test("User ID is a number", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.id).to.be.a('number');
});
Explanation:
pm.expect(jsonData.id).to.be.a('number')
: Asserts that theid
property is of typenumber
.
• Example: Checking Response Properties
Scenario:
An endpoint GET https://api.example.com/users/12345
returns user details. You want to ensure that the response contains specific properties with correct data types.
Creating the Request:
- Create a new request named “Get User Details”.
- Set the HTTP method to
GET
. - Enter the URL:
https://api.example.com/users/12345
. - Click “Save”.
Writing the Tests:
Navigate to the “Tests” tab and add the following script:
pm.test("Response has required properties", function () {
var jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("id");
pm.expect(jsonData).to.have.property("name");
pm.expect(jsonData).to.have.property("email");
});
pm.test("Data types are correct", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.id).to.be.a('number');
pm.expect(jsonData.name).to.be.a('string');
pm.expect(jsonData.email).to.be.a('string');
});
Explanation:
- First Test: Ensures that the response contains
id
,name
, andemail
properties. - Second Test: Validates that
id
is a number, whilename
andemail
are strings.
Running the Tests:
- Click “Send” to execute the request.
- Check the “Test Results”:
- All tests pass: The response meets the expected structure and data types.
- Any test fails: Indicates discrepancies in the response.
5. JSON Schema Validation
While individual assertions are effective for simple validations, JSON Schema provides a comprehensive way to validate the entire structure of a JSON response against a predefined schema.
• Introduction to JSON Schemas
A JSON Schema is a blueprint that defines the structure, required properties, data types, and constraints of a JSON document. It ensures that the API responses adhere to the expected format, enhancing reliability and consistency.
Benefits of Using JSON Schemas:
- Comprehensive Validation: Checks the entire response structure.
- Maintainability: Easier to manage and update tests as schemas evolve.
- Reusability: Schemas can be reused across multiple tests and collections.
• Writing and Validating Schemas
Step 1: Define the JSON Schema
Create a schema that mirrors the expected structure of the API response.
Example Schema for User Details:
{
"type": "object",
"required": ["id", "name", "email"],
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"email": {
"type": "string",
"format": "email"
}
},
"additionalProperties": false
}
Explanation:
- type: The response should be a JSON object.
- required: Specifies mandatory properties (
id
,name
,email
). - properties: Defines each property’s data type and constraints.
id
: Must be an integer.name
: Must be a string.email
: Must be a string following email format.
- additionalProperties: Disallows any properties not defined in the schema.
Step 2: Add Schema Validation in Postman
Navigate to the “Tests” tab of your request and add the following script:
const schema = {
"type": "object",
"required": ["id", "name", "email"],
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"email": {
"type": "string",
"format": "email"
}
},
"additionalProperties": false
};
pm.test("JSON Schema is valid", function () {
pm.response.to.have.jsonSchema(schema);
});
Explanation:
- schema: Defines the expected JSON structure.
pm.response.to.have.jsonSchema(schema)
: Validates the response against the defined schema.
Running the Test:
- Click “Send” to execute the request.
- Check the “Test Results”:
- Pass: The response adheres to the schema.
- Fail: The response deviates from the schema, indicating issues.
• Using Mock Servers for Schema Testing
Mock Servers allow you to simulate API responses, enabling you to test your schemas without relying on the actual API’s availability or behavior.
Creating a Mock Server:
- Save an Example Response:
- Select a request in your collection.
- Click “Save Response” after sending a successful request.
- Name the example (e.g., “User Details Example”).
- Create the Mock Server:
- Hover over your collection and click on the ellipsis (…).
- Select “Mock Collection”.
- Name your mock server and choose the workspace.
- Click “Create Mock Server”.
- Configure the Mock Server:
- Replace the original API URL with the mock server’s URL in your requests.
- This ensures that when you run the collection, it uses the mock responses.
Testing with Mock Servers:
- Modify the mock responses to introduce intentional errors.
- Run your tests to ensure that schema validations catch these discrepancies.
- This practice enhances your ability to identify and rectify issues proactively.
6. Automating API Tests with Collection Runner
Manually executing each request in a collection can be time-consuming, especially as your API grows. Postman’s Collection Runner automates this process, allowing you to run multiple requests sequentially and view aggregated results.
• Running Collections Manually
Step 1: Open Collection Runner
- Select your collection in Postman.
- Click on the “Run” button or the “Collection Runner” icon.
Step 2: Configure the Run
- Choose Requests: Select specific requests or run the entire collection.
- Select Environment: Choose the environment with relevant variables.
- Iterations: Define how many times you want to run the collection (default is 1).
- Delay: Set a delay between requests if necessary.
Step 3: Execute the Run
Click “Run [Collection Name]” to start the execution. Postman will sequentially send each request and display the results in real-time.
• Handling Test Failures
When running a collection, some tests might fail due to various reasons like incorrect responses, schema mismatches, or API issues. Understanding and handling these failures is crucial.
Identifying Failures:
- Red Indicators: Tests that fail will be marked in red.
- Detailed Logs: Click on failed tests to view detailed error messages and response snippets.
Example: Handling a Failed Status Code Test
If a test expecting a 200
status code fails, it indicates that the API returned an unexpected status, such as 404
or 500
. This requires immediate attention to identify and fix the underlying issue.
• Persisting Responses
By default, Postman doesn’t save responses during Collection Runs to optimize performance. However, persisting responses can be beneficial for debugging and analysis.
Enabling Response Persistence:
- Open the Collection Runner.
- Click on “Run Settings”.
- Toggle “Persist Responses” to ON.
Benefits:
- Debugging: Access response bodies for failed tests.
- Analysis: Review response data for patterns or anomalies.
Note: Persisting responses may impact performance, especially with large collections or numerous iterations.
7. Scheduling Automated Runs
Automating your API tests ensures continuous validation, catching issues promptly without manual intervention. Postman offers scheduling capabilities to run collections at predefined intervals using its cloud-based runner.
• Setting Up Scheduled Runs
Step 1: Open Collection Settings
- Hover over your collection and click on the ellipsis (…).
- Select “Run Collection”.
Step 2: Configure the Schedule
- Name Your Schedule: Provide a descriptive name (e.g., “Daily API Health Check”).
- Select Run Frequency:
- Hourly
- Daily
- Weekly
- Custom Intervals
- Choose the Environment: Ensure the correct environment with necessary variables is selected.
- Configure Notifications:
- Email Alerts: Receive notifications on test failures.
- Team Notifications: Share results with team members.
Step 3: Activate the Schedule
Click “Schedule Run” to activate. Postman will now execute the collection automatically based on your defined frequency.
• Configuring Notifications
Why Notifications?
Automated notifications keep you informed about the health and performance of your APIs, allowing for swift responses to any detected issues.
Setting Up Email Notifications:
- In the Scheduled Run configuration, navigate to “Notifications”.
- Enable Email Alerts and specify the email addresses to receive updates.
- Customize the notification message if desired.
Example: Email Alert for Failed Tests
Subject: [Postman] API Test Failure Alert
Body:
Hello Team,
The latest scheduled run of the "Daily API Health Check" has detected failures in the following tests:
- Create New Order
- Get User Details
Please investigate the issues at your earliest convenience.
Best,
Postman Automation
Explanation:
This email alert notifies the team about specific test failures, enabling timely troubleshooting and resolution.
• Managing Secrets and API Keys
Ensuring the security of your API keys and secrets is paramount, especially when scheduling automated runs.
Best Practices:
- Use Environment Variables: Store secrets in environment variables, avoiding hardcoding sensitive data.
- Limit Access: Restrict access to environments containing secrets to authorized team members only.
- Regular Rotation: Periodically rotate API keys to minimize security risks.
Example: Storing API Keys Securely
- Create an Environment Variable named
apiKey
. - Set the Initial Value to your actual API key.
- Use the Variable in your requests:
{{apiKey}}
.
This approach ensures that API keys remain secure and can be easily managed across different environments.
8. Utilizing Postman CLI for Automation
The Postman Command Line Interface (CLI), known as Newman, allows you to run Postman collections directly from the terminal. This facilitates integration with CI/CD pipelines and enables more flexible automation scenarios.
• Installing Postman CLI
Step 1: Install Node.js and npm
Newman is a Node.js-based tool, so you need to have Node.js and npm installed.
- Download Node.js from the official website.
- Install by following the installation prompts for your operating system.
Step 2: Install Newman Globally
npm install -g newman
Explanation:
npm
: Node Package Manager, used to install packages.install -g
: Installs Newman globally, making it accessible from any directory.newman
: The Postman CLI tool.
Step 3: Verify Installation
newman -v
This should display the current version of Newman, confirming a successful installation.
• Running Collections via CLI
With Newman installed, you can execute Postman collections directly from the terminal.
Basic Command Structure:
newman run <collection.json> -e <environment.json>
Explanation:
newman run
: Initiates the collection run.<collection.json>
: Path to your exported Postman collection.-e <environment.json>
: (Optional) Path to your exported environment.
Example: Running a Collection
newman run my_api_tests.postman_collection.json -e dev_environment.postman_environment.json
Explanation:
This command runs the my_api_tests
collection using the dev_environment
environment, executing all defined requests and tests.
• Postman CLI Options
Newman offers various options to customize your collection runs, enhancing flexibility and control.
Common Options:
Option | Description |
---|---|
-r or --reporters |
Specifies the reporter(s) to use (e.g., cli , json , html ). |
--iteration-count |
Sets the number of iterations to run the collection. |
--delay-request |
Adds a delay (in milliseconds) between each request. |
--timeout |
Sets a timeout limit for requests. |
--folder |
Runs only specific folders within the collection. |
Example: Using Reporters and Iterations
newman run my_api_tests.postman_collection.json -e dev_environment.postman_environment.json -r cli,json --iteration-count 5
Explanation:
-r cli,json
: Generates reports in both CLI and JSON formats.--iteration-count 5
: Executes the collection five times.
Advanced Usage: Filtering by Folder
newman run my_api_tests.postman_collection.json -e dev_environment.postman_environment.json --folder "User Endpoints"
Explanation:
Runs only the requests within the “User Endpoints” folder, allowing targeted testing.
9. Integrating Postman Tests with CI/CD
Integrating Postman tests into your Continuous Integration/Continuous Deployment (CI/CD) pipelines ensures that your APIs are consistently validated during development and deployment processes. This automation enhances reliability and accelerates the delivery of quality software.
• Overview of CI/CD
CI/CD stands for Continuous Integration and Continuous Deployment, representing a set of practices that enable rapid and reliable software delivery.
- Continuous Integration (CI): Developers frequently integrate code changes into a shared repository, triggering automated builds and tests to detect issues early.
- Continuous Deployment (CD): Automated deployment of code changes to production environments after passing all tests, ensuring swift delivery of new features and fixes.
Benefits of CI/CD:
- Speed: Accelerates the development and deployment process.
- Reliability: Reduces human errors through automation.
- Consistency: Ensures uniform testing and deployment procedures.
- Feedback: Provides immediate insights into code quality and functionality.
• Running Tests with GitHub Actions
GitHub Actions is a popular CI/CD tool integrated within GitHub repositories, allowing automation of workflows like building, testing, and deploying code.
Step 1: Create a GitHub Repository
- Sign in to GitHub or create an account.
- Click on “New” to create a new repository.
- Name your repository (e.g., “my-api-project”) and set its visibility (public or private).
- Click “Create Repository”.
Step 2: Configure GitHub Actions Workflow
- Navigate to Your Repository on GitHub.
- Click on the “Actions” tab.
- Click “Set up a workflow yourself” or choose a template.
- Create a `.yml` file (e.g.,
postman-tests.yml
) in the.github/workflows/
directory.
Step 3: Define the Workflow
Add the following configuration to your .yml
file:
name: Postman API Tests
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
postman-tests:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v2
- name: Install Newman
run: npm install -g newman
- name: Run Postman Collection
run: newman run my_api_tests.postman_collection.json -e dev_environment.postman_environment.json
env:
NEWMAN_POSTMAN_API_KEY: ${{ secrets.POSTMAN_API_KEY }}
Explanation:
- name: Names the workflow “Postman API Tests”.
- on: Specifies triggers—runs on pushes and pull requests to the
main
branch. - jobs: Defines a job named
postman-tests
running on the latest Ubuntu environment. - steps:
- Checkout Repository: Uses GitHub’s checkout action to pull the repository’s code.
- Install Newman: Installs Newman globally using npm.
- Run Postman Collection: Executes the Postman collection with the specified environment.
Step 4: Manage Secrets
- Generate a Postman API Key:
- In Postman, navigate to “Settings” > “API Keys”.
- Click “Generate API Key” and name it (e.g., “GitHub Actions Key”).
- Copy the API key; you’ll need it for GitHub.
- Add the API Key to GitHub Secrets:
- In your GitHub repository, go to “Settings” > “Secrets” > “Actions”.
- Click “New repository secret”.
- Name:
POSTMAN_API_KEY
- Value: Paste the copied API key.
- Click “Add secret”.
Step 5: Commit and Push the Workflow
Once your workflow file is configured and secrets are set, commit and push the .yml
file to your repository.
Step 6: Monitor the Workflow
- Navigate to the “Actions” tab in your repository.
- Select the workflow to view its execution.
- Review the Results:
- Success: All tests passed, indicating a healthy API.
- Failure: Some tests failed, necessitating investigation.
Example: Failed Test Notification
❌ Postman API Tests
Run Postman Collection
✓ Install Newman
✗ Run Postman Collection
1 failed, 2 passed
Error Details:
- Test "Status code is 200" failed: Expected status code 200 but got 500
Explanation:
This notification highlights that the “Status code is 200” test failed because the API returned a 500 Internal Server Error
, prompting immediate attention.
• Running Tests with Other CI/CD Tools
While GitHub Actions is a popular choice, Postman CLI can integrate seamlessly with other CI/CD platforms like Jenkins, GitLab CI, CircleCI, and Travis CI. Here’s a brief overview of how to integrate with these tools:
Jenkins
- Install Node.js on the Jenkins server.
- Install Newman Globally:
npm install -g newman
- Create a Jenkins Pipeline that:
- Checks out the repository.
- Installs Newman.
- Runs the Postman collection:
newman run my_api_tests.postman_collection.json -e dev_environment.postman_environment.json
GitLab CI
- Define a `.gitlab-ci.yml` file in your repository.
- Configure the Job:
postman_tests: stage: test image: node:latest script: - npm install -g newman - newman run my_api_tests.postman_collection.json -e dev_environment.postman_environment.json
CircleCI
- Create a `.circleci/config.yml` file.
- Set Up the Job:
version: 2.1 jobs: postman_tests: docker: - image: circleci/node:latest steps: - checkout - run: name: Install Newman command: npm install -g newman - run: name: Run Postman Collection command: newman run my_api_tests.postman_collection.json -e dev_environment.postman_environment.json workflows: version: 2 test: jobs: - postman_tests
Explanation:
Each CI/CD tool requires defining a configuration file specifying the steps to install Newman and execute the Postman collection. Refer to each tool’s documentation for advanced configurations and optimizations.
10. Collaborating in Postman Workspaces
Collaboration is key in API development, enabling teams to work together efficiently. Postman offers Workspaces—shared environments where team members can collaborate on collections, share environments, and communicate seamlessly.
• Creating Team Workspaces
- Create a Workspace
- Click on the “Workspaces” dropdown in the top-left corner.
- Select “Create Workspace”.
- Name Your Workspace (e.g., “API Development Team”).
- Choose the Type:
- Personal: Private to you.
- Team: Shared with your team members.
- Add Team Members: Invite collaborators by entering their email addresses.
- Click “Create Workspace”.
Step 2: Share Collections
- Select a Collection within the workspace.
- Click on the ellipsis (…) next to the collection name.
- Choose “Share Collection”.
- Set Permissions for each team member:
- Viewer: Can view but not edit.
- Editor: Can view and edit.
- Click “Share” to finalize.
Team Workspaces foster collaboration, ensuring that all team members have access to the latest API tests and can contribute effectively.
• Forking and Merging Collections
Forking allows team members to create personal copies of collections to experiment or develop new tests without affecting the original collection.
Creating a Fork:
- Select the Collection to fork.
- Click on the ellipsis (…) and choose “Fork Collection”.
- Name the Fork (e.g., “User Authentication Tests”).
- Select the Workspace where the fork should reside.
- Click “Fork Collection”.
Merging Changes:
After making changes in the forked collection, integrate them back into the original collection to maintain consistency.
Steps to Merge:
- Navigate to the Forked Collection.
- Click on the ellipsis (…) and select “Merge Collection”.
- Review Changes: Postman will display the differences between the fork and the original.
- Resolve Conflicts: Decide which changes to keep if there are conflicting edits.
- Click “Merge” to integrate the changes.
Explanation:
Merging ensures that valuable contributions from team members are incorporated into the main collection, enhancing the overall quality and coverage of your API tests.
• Managing Team Collaboration
Effective collaboration involves clear communication, version control, and access management. Postman provides tools to facilitate these aspects:
- Comments: Add comments to requests or collections to discuss changes, provide feedback, or highlight issues.
- Version Control: Track changes, revert to previous versions, and maintain a history of modifications.
- Access Control: Manage who can view, edit, or administer collections and environments within the workspace.
Example: Adding a Comment
User Authentication Tests - Request #5
"Consider adding a test for token expiration to enhance security checks."
Explanation:
Comments enable team members to provide actionable feedback directly within the collection, fostering a collaborative environment and ensuring continuous improvement.
11. Assignments and Hands-On Practice
Practical assignments reinforce learning, enabling you to apply concepts and techniques in real-world scenarios. Below are several assignments designed to enhance your Postman API Testing skills.
• Assignment #2: Writing Status Code Tests
Objective:
Ensure that every API request in your collection includes a test verifying the correct HTTP status code.
Instructions:
- Navigate to the Original Workspace and Fork the Collection named “Assignment 2”.
- For Each Request in the collection:
- Open the “Tests” tab.
- Write a Test to assert the expected status code.
- Name the Test appropriately (e.g., “Status code is 200”).
- Verify that all tests pass by running the collection manually.
- Save and Commit your changes.
Example Test Script:
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
Explanation:
This test confirms that the API returns a 200 OK
status, indicating a successful request.
• Assignment #3: Testing Orders Endpoint
Objective:
Develop comprehensive tests for the “Orders” endpoint, ensuring data integrity and adherence to business logic.
Instructions:
- Access the “Orders” Endpoint within your collection.
- Write Tests to:
- Verify the response status code.
- Ensure the response body is valid JSON.
- Assert that specific properties (e.g.,
orderId
,customerName
,items
) exist and have correct data types. - Validate business rules (e.g.,
totalPrice
should be greater than zero).
- Run the Tests using the Collection Runner and review the results.
- Adjust Tests as needed based on test outcomes.
- Save and Commit your changes.
Example Test Script:
pm.test("Response is JSON", function () {
pm.response.to.be.json;
});
pm.test("Order ID is a string", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.orderId).to.be.a('string');
});
pm.test("Total Price is greater than zero", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.totalPrice).to.be.above(0);
});
Explanation:
- Response is JSON: Ensures the API returns a JSON response.
- Order ID is a string: Validates the data type of
orderId
. - Total Price is greater than zero: Confirms business logic that orders must have a positive total price.
• Assignment #4: Creating JSON Schemas
Objective:
Design and implement JSON Schemas to validate the structure of API responses, ensuring comprehensive coverage.
Instructions:
- Identify the API Endpoint you want to validate (e.g., “Get User Details”).
- Define a JSON Schema that mirrors the expected response structure.
- Add Schema Validation to the corresponding request’s “Tests” tab.
- Run the Tests to ensure the schema correctly validates responses.
- Modify Mock Responses to test schema validation robustness.
- Save and Commit your changes.
Example Schema for User Details:
{
"type": "object",
"required": ["id", "name", "email"],
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"email": {
"type": "string",
"format": "email"
}
},
"additionalProperties": false
}
Explanation:
This schema ensures that the response contains id
, name
, and email
properties with specified data types and no additional properties.
• Assignment #5: Integrating with GitHub Actions
Objective:
Automate the execution of Postman tests within a CI/CD pipeline using GitHub Actions, ensuring continuous validation of your APIs.
Instructions:
- Create a GitHub Repository and push your Postman collections and environment files.
- Set Up GitHub Actions by creating a workflow file (
.github/workflows/postman-tests.yml
). - Configure the Workflow to:
- Checkout the repository.
- Install Newman.
- Run the Postman collection with the appropriate environment.
- Manage Secrets by adding your Postman API key to GitHub Secrets.
- Commit and Push the workflow file to trigger the pipeline.
- Monitor the Workflow under the “Actions” tab to ensure tests run successfully.
- Review Test Results and address any failures promptly.
Example Workflow File (postman-tests.yml
):
name: Postman API Tests
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
postman-tests:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v2
- name: Install Newman
run: npm install -g newman
- name: Run Postman Collection
run: newman run my_api_tests.postman_collection.json -e dev_environment.postman_environment.json
env:
NEWMAN_POSTMAN_API_KEY: ${{ secrets.POSTMAN_API_KEY }}
Explanation:
- name: Names the workflow “Postman API Tests”.
- on: Specifies triggers—runs on pushes and pull requests to the
main
branch. - jobs: Defines a job named
postman-tests
running on the latest Ubuntu environment. - steps:
- Checkout Repository: Uses GitHub’s checkout action to pull the repository’s code.
- Install Newman: Installs Newman globally using npm.
- Run Postman Collection: Executes the Postman collection with the specified environment.
• Assignment #6: Running Tests in Other CI/CD Tools
Objective:
Expand your automation skills by integrating Postman tests with various CI/CD platforms, enhancing your testing pipeline’s flexibility.
Instructions:
- Choose a CI/CD Tool (e.g., Jenkins, GitLab CI, CircleCI).
- Set Up the Environment:
- Install Node.js and Newman if required.
- Configure environment variables and secrets securely.
- Define the CI/CD Pipeline to:
- Checkout the repository.
- Install Newman.
- Execute the Postman collection with the appropriate environment.
- Test the Integration by making code changes that trigger the pipeline and ensure tests run as expected.
- Monitor and Troubleshoot any issues arising from the integration.
Example: GitLab CI Configuration (.gitlab-ci.yml
)
stages:
- test
postman_tests:
stage: test
image: node:latest
script:
- npm install -g newman
- newman run my_api_tests.postman_collection.json -e dev_environment.postman_environment.json
Explanation:
This configuration defines a pipeline stage that installs Newman and runs the Postman collection, utilizing environment variables for secure API key management.
12. Conclusion and Next Steps
Congratulations on completing this comprehensive guide to Postman API Testing! You’ve gained valuable insights into setting up Postman, writing effective tests, automating processes, integrating with CI/CD pipelines, and collaborating within teams. Here’s how you can take your newfound knowledge forward.
• Claiming Your Postman Badge
Objective:
Earn recognition for your expertise by claiming your Postman badge upon completing the course.
Steps:
- Complete All Assignments: Ensure you’ve successfully completed and submitted all the hands-on assignments.
- Navigate to the Original Workspace: Go to the workspace where you forked the “Claim Your Badge” collection.
- Fork the “Claim Your Badge” Collection and follow the detailed instructions within to finalize your badge claim.
- Submit Your Badge: Follow any submission guidelines provided to receive your official Postman badge.
Earning this badge showcases your proficiency in API testing and enhances your professional profile.
• Continuing Your Learning Journey
API testing and automation are continually evolving fields. To stay ahead, consider the following steps:
- Explore Advanced Features: Dive deeper into Postman’s advanced features like scripting, pre-request scripts, and more intricate JSON Schema validations.
- Learn Other Tools: Familiarize yourself with complementary tools like Swagger for API documentation or Jenkins for more complex CI/CD integrations.
- Join Communities: Engage with the Postman community through forums, webinars, and meetups to exchange knowledge and stay updated on best practices.
- Practice Regularly: Continuously apply your skills by working on diverse API projects, contributing to open-source initiatives, or developing your own APIs.
- Stay Updated: Follow Postman’s official blog and documentation to keep abreast of new features and updates.
Your journey in API testing is just beginning. Embrace continuous learning to excel and make impactful contributions in the tech landscape.