API testing is a crucial aspect of software development, ensuring that backend services function correctly before deployment. Postman is a widely used tool for manual API testing, whereas Newman extends its capabilities by enabling automated API testing via the command line.
In this comprehensive guide, we will cover:
✅ Installing Postman and Newman CLI ✅ Creating API test collections ✅ Automating testing using Newman scripts
By the end of this guide, you will have a fully automated API testing workflow using Postman and Newman.
1. Installing Postman and Newman CLI
1.1 Install Postman
Postman can be downloaded from the official Postman website. After installation, launch Postman and sign in to your account.
1.2 Install Newman
Newman is a CLI tool that allows you to run Postman collections in an automated manner. To install Newman globally on your system, use the following command:
npm install -g newman
To verify installation, run:
newman -v
This will display the installed version of Newman.
2. Creating API Test Collections
2.1 Creating a New Collection
- Open Postman and create a new collection.
- Add multiple API requests (GET, POST, PUT, DELETE) to the collection.
- Use Pre-request scripts and Tests to validate API responses.
Example test script in Postman:
tests["Status code is 200"] = responseCode.code === 200;
tests["Response time is acceptable"] = responseTime < 2000;
2.2 Exporting the Collection
Once the collection is created and tested manually, export it as a JSON file:
- Click on the collection menu (⋮) > Export.
- Save it in your project directory.
3. Automating Testing Using Newman Scripts
3.1 Running the Collection with Newman
Execute the exported collection using Newman:
newman run collection.json
To include an environment file:
newman run collection.json -e environment.json
3.2 Generating Reports
Newman supports multiple reporting formats. For HTML reports:
newman run collection.json -r html --reporter-html-export report.html
For JUnit reports:
newman run collection.json -r junit --reporter-junit-export results.xml
3.3 Integrating with CI/CD Pipelines
Newman can be integrated with GitHub Actions, GitLab CI/CD, Jenkins, or Azure DevOps to automate API tests in CI/CD workflows. Example GitHub Actions workflow:
name: API Tests
on: [push]
jobs:
api-tests:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Install Newman
run: npm install -g newman
- name: Run API tests
run: newman run collection.json --reporters cli,junit --reporter-junit-export results.xml
Conclusion
Postman and Newman provide a powerful combination for local and automated API testing. We covered:
- Installing Postman and Newman CLI
- Creating and exporting API test collections
- Automating API tests using Newman
By implementing these practices, you can ensure your APIs are reliable, well-tested, and ready for deployment.