What are the different types of API testing?
There are many ways to test an API, and each one serves a unique purpose. The following list represents four of the most common approaches, but there are endless variations within each category that teams can use to build a customized API testing strategy.
Contract testing
An API contract is a human- and machine-readable representation of an API’s intended functionality. It establishes a single source of truth for what each request and response should look like—and forms the basis of service-level agreements (SLAs) between producers and consumers. API contract testing helps ensure that new releases don’t violate the contract by checking the content and format of requests and responses.
Unit testing
API unit testing is the process of confirming that a single endpoint returns the correct response to a given request. Unit tests may validate that an endpoint handles optional parameters correctly, or that it returns the appropriate error message when sent an invalid request.
End-to-end testing
Whereas unit tests help developers ensure that individual endpoints are working as expected, end-to-end tests are used to validate key user journeys that may involve multiple endpoints and APIs. End-to-end API testing involves chaining requests together and confirming that each one is working properly, which helps teams surface issues in complex workflows before users do.
Load testing
API load testing enables developers to confirm whether their API is able to operate reliably during times of peak traffic. It typically involves using a testing tool to simulate large request volumes and measure the resulting response times and error rates. This type of testing is often performed in anticipation of a significant load increase, such as right before a product launch or yearly sale.
Using pm.response in Postman for API Testing
pm.response
is a crucial object in Postman scripting that provides a wide array of information about the response returned from your API request. Understanding how to effectively use
pm.response
can significantly enhance your API testing by allowing you to access and validate various aspects of the response data. Here’s a more detailed look at utilizing
pm.response
in your tests:
Accessing Response Attributes
pm.response
contains several properties and methods that give you access to different parts of the API response, such as the status code, response time, headers, and body. Here’s how you can use them:
-
Status Code: Access the status code of the response to verify if the API request was successful.
let statusCode = pm.response.code; pm.expect(statusCode).to.eql(200);
-
Response Time: Check how long the API took to respond, which is crucial for performance testing.
let responseTime = pm.response.responseTime; pm.expect(responseTime).to.be.below(500); // time in milliseconds
-
Headers: Examine the response headers for important metadata like content type, caching policies, and more.
let contentTypeHeader = pm.response.headers.get("Content-Type"); pm.expect(contentTypeHeader).to.include("application/json");
-
Body: The response body contains the data returned by the API. You can parse this data and make assertions based on your API’s expected output.
let responseBody = pm.response.json(); // For JSON response pm.expect(responseBody).to.have.property("name", "John Doe");
Using pm.response for Complex Validations
Beyond simple assertions, pm.response can be used for more complex validations:
- Validating Response Structure: Ensure the response body follows a specific schema or structure.
- Conditional Testing: Perform different tests based on certain response conditions. For example, if the status code is 200, check one set of criteria; if it’s 400, check another.
- Dynamic Data Validation: Sometimes, responses contain dynamic data (like timestamps or unique IDs). Use pm.response to validate the format of these dynamic elements without hardcoding the values.
Best Practices with pm.response
- Readability: Keep your tests readable and straightforward. Complex logic can make tests more complicated to understand and maintain.
- Error Handling: Include error handling in your tests. For example, check if the response body is present before trying to parse it.
- Consistency: Be consistent in how you use pm.response across different tests. This consistency helps in maintaining and scaling your test suite.
Listing/New Request
This test would be a little different. According to the requirement of our fictitious API, only logged in users can create listings. So we would need a way to authenticate the request.
Recall when signing in a JWT token was returned we can use that token as the authorization header for the create listing request.
To do this in postman, simply copy the token you got from signing in and go over to the
Authorization
tab of the Request section in Postman and select the type to be
Bearer Token
from the Type dropdown. You can then paste the token in the box to your right labeled
Token
. So the new request Authorization tab should look like this:
You can then go on and add the parameters in the Body tab of the request. You will notice the fields name are already there with sample values which you can choose to edit or not. Let’s make a request first before writing our test. A successful response will look like so:
{ "message": "New listing created successfully", "data": { "createdAt": 1596637153470, "updatedAt": 1596637153470, "id": "41d922ce-7326-43eb-93c8-31658c59e45d", "name": "Glorious Lounge", "type": "Hotel", "address": "No 1. Something street", "rent": "$100k per year", "lister": "9fa2e648-1db5-4ea9-89a1-3be5bc73cb34" } }
We can see we get a JSON response body back. We can test for that and also make sure data is not empty. Add the following test case to the Test tab:
pm.test("Status code is 200", function () { pm.response.to.have.status(200); }); pm.test("Response has a JSON body", function () { pm.response.to.be.json; }); pm.test("Response has a message property", function () { var jsonData = pm.response.json(); pm.expect(jsonData.message).to.be.a('string'); }); pm.test("Response has a data property", function () { var jsonData = pm.response.json(); pm.expect(jsonData.data).to.be.a('object'); });
With that added, make another request and the tests should all pass as shown below:
What are the benefits of API testing?
API testing plays a crucial role in modern software development workflows, and its benefits cannot be overstated. These benefits include:
- Quality assurance: API testing helps preserve consumer trust and protect the business’s reputation by enabling teams to continuously ensure their API performs as expected.
- Early issue detection and resolution: A shift-left approach to API testing allows teams to identify defects as soon as they are introduced. This makes the development process more predictable and helps teams stay on schedule.
- Resource conservation: More and more teams are automating their approach to API testing, which saves time and allows team members to focus their bandwidth on innovation.
- Rapid iteration: Many teams execute their API tests within CI/CD pipelines, which enables them to automatically validate every code change before it reaches production. This approach supports more frequent releases while reducing the risk of bugs and regressions.
How to Test API Using Postman?
Here is a detailed step-by-step guide on testing your API with Postman.
StepSign up for a Postman Account
The first step is to create an account on Postman. You can create an account by downloading the Postman on Windows/MacOS or using the Postman online.
StepCreate a New Request
Once you have installed Postman, you can create a new request by clicking the “New” button in the top left corner of the Postman window. Select ” HTTP Request” to create a new request.
StepEnter Request Methods, Parameters
Next, you need to enter the details of the API request you want to test. It includes the URL, HTTP methods, and any parameters or headers the API requires. You can also add a request body if required. Creating a GET request for Postman API testing as an example.
StepSend the Request
Once you have entered the request details, click the “Send” button in Postman to send the request to test the API. Postman will display the response in the interface, including the response status, headers, and body.
StepCreate a Postman Collection
One of the key features of Postman is the Collection Runner, which allows developers to execute multiple requests in a single run. With the Collection Runner, you can specify variables, set up test suites, and generate reports to track the results of your API testing.
If you want to test multiple API requests, you can create a collection to group them. To create a collection, click the “New” button and select “Collection”. Give the collection a name and description to help you remember.
StepAdd Requests to the Collection
Once you have created a collection, you can add requests by clicking the “Add Request” button. Enter the request details as before, and click the “Save” button to save the request to the collection.
StepUse the Postman Collection Runner
Postman’s Collection Runner feature allows you to simultaneously run multiple requests in a collection. To use the Collection Runner, click on the “Runner” button in the top right corner of the Postman window. Select the collection you want to run, and click the “Start Run” button.
StepAnalyze the Test Results
Once the Collection Runner has finished running the requests, Postman will display the test results in the interface. You can see which requests passed and failed and view detailed information about each request.
Postman has recently limited their Collection Runner functionality, which has caused frustration for many users who rely on it for API testing. As a result, developers are now seeking alternatives to Postman that offer similar or better features. One such alternative is Apidog, which offers a range of advanced features not available in Postman. In this article, we will explore the advantages of Apidog over Postman and how it can improve your API testing experience.
Apidog: The Best Postman API Testing Alternative
Apidog is a free API testing tool that provides developers with advanced features to ensure their APIs’ functionality, reliability, and security. With Apidog, you can create custom test scenarios without limitation, and generate detailed reports. These advanced features allow developers to thoroughly test their APIs and identify potential issues before they reach production.
Apidog also offers a collaborative environment, making it easier for teams to work together on API testing projects. Multiple team members can work on the same project simultaneously, and changes are automatically synced in real-time, reducing the risk of errors and improving team efficiency.
Cách chạy Collection sử dụng Runner
Có hai cách để chạy một collection đó là sử dụng Collection Runner và Newman. Hãy bắt đầu thực thi collection bằng Collection Runner.
Bước 1: Kích nút Runner ở góc trên bên cạnh nút Import
Bước 2: Trang Collection Runner sẽ xuất hiện như ở bên dưới. Theo các mô tả ở các trường bên dưới.
Bước 3: Chạy Postman Test Collection bằng cách thiết lập sau:
- Chọn Postman test collection- Thiết lập Iterations là 3
- Thiết lập Delay là 2500 ms
- Kích nút Run Postman Test…
Bước 4 Trang kết quả chạy sẽ được hiển thị sau hi kích nút Run. Phụ thuộc và delay, bạn sẽ nhìn thấy kết quả mà chúng thực hiện.
- Khi test kết thúc, bạn có thể nhìn thấy trạng thái nếu nó Passed hoặc Failed và kết quả mỗi lần lặp (iteration).
- Bạn nhìn thấy trạng thái Pass cho các request GET
- Khi chúng ta không có bất kỳ thử nghiệm nào cho POST, sẽ có một message hiển thị “This request did not have any tests”.
Bạn có thể thấy tầm quan trọng của việc có các test trong các requesst để bạn có thể xác minh trạng thái HTTP nếu thành công và dữ liệu được tạo hoặc truy xuất.
Kết luận
Bài viết trên đây cho bạn biết cách sử dụng cơ bản của POSTMAN, một công cụ rất tuyệt vời giúp cho các developer khi cần test cách truyền params hoặc kết quả respond từ API trả về.
Tham khảo
https://www.guru99.com/postman-tutorial.html
https://www.toolsqa.com/postman/basic-authentication-in-postman/
All Rights Reserved
API Testing sử dụng Postman
Bài đăng này đã không được cập nhật trong 2 năm
Hiện nay có rất Tool hỗ trợ cho việc kiểm thử API. Phải kể đến như Jmeter, Curl, Postman….. Trong bài viết hôm nay mình sẽ tìm hiểu về Postman, cách cài đặt cũng như sử dụng nó trong kiểm thử API.
I . API là gì? Vì sao phải test API?
Khái niệm
API (Application Programming Interface) ta có thể hiểu đơn giản nó là phần mềm trung gian giữa Client và Server cho phép chúng có thể nói chuyện được với nhau.
Ví dụ cụ thể, khi bạn dùng facebook hay gửi một tin nhắn, kiểm tra thời tiết trên điện thoại đi động, lúc đó chính là bạn đang sử dụng API.
Trong API, thường sử dụng giao thức để Client và server giao tiếp với nhau. Trong đó giao thức chính là HTTP. Và API được xây dựng trên chính 2 thành phần: Request và Reponse.
Một request thường sử dụng 4 phương thức chính đó là:
- GET để truy vấn object
- POST để tạo object mới
- PUT để sửa đổi hoặc thay thế một object
- DELETE để loại bỏ một object
Mỗi phương thức trên phải được API call thông qua để gửi chỉ thị cho server phải làm gì.
API documentation
Make documentation a core part of your API workflow with Postman’s automatic documentation features. Postman supports markdown-enabled and machine-readable documentation through the Postman Collection format, and you can generate docs through your OpenAPI files as well. Your docs will automatically include detail on your requests, with sample code in various client languages. You can share the docs with your team or with the world through workspaces or publish them in a dedicated portal.
What is the future of API testing?
Postman’s State of the API report indicates that developers, product managers, and other technical stakeholders are spending more of their time on API-related work. This trend points to the growing importance of APIs—and, by extension, API testing—to every company’s digital strategy. As API testing becomes more ingrained in teams’ workflows, it’s likely that we’ll see increased automation, a greater emphasis on API security testing, and a stronger push towards standardized testing practices within organizations.
What are some API testing best practices?
There are several best practices that teams should follow to implement an API testing strategy that is efficient and sustainable. These best practices are:
Create a dedicated testing environment
It’s crucial for teams to perform API testing in a dedicated environment before they push changes to production. This approach enables them to contain any issues and avoid user-facing downtime. The testing environment should mirror production conditions as closely as possible, but it should include mock data that can be safely manipulated and replaced when necessary.
Automate your API tests
While manual API testing can help developers debug specific problems, test automation enables teams to systematize their approach in order to ensure consistent coverage and reduce the possibility of human error. Teams can use a variety of tools to create test suites and schedule executions to occur at specific times, at specific frequencies, or in CI/CD pipelines after every commit or push.
Run tests throughout the API lifecycle
The traditional approach to API testing, which occurs once the development process is complete, can allow issues to go undetected until they are deeply ingrained and difficult to fix. Teams should therefore run API tests at every stage of the API lifecycle. Certain test types will be more relevant at different stages; for instance, contract tests are typically written at the design stage and executed against all future iterations, while unit tests are usually written and executed during development and in CI/CD pipelines. Running tests early and often helps teams surface and remediate issues as quickly as possible so that they can deliver high-quality APIs to consumers.
Write reusable subtests
While every API endpoint serves a unique purpose and should therefore be tested with custom logic, there may be certain rules that are universally applicable. For instance, teams may wish to specify that every request must return a response in a certain amount of time, or that all responses must be formatted in JSON. Rather than implementing this logic over and over again, they can create subtests that can be reused throughout their test suite. This approach reduces the risk of human error and ensures consistency in how each endpoint is tested.
Keep your tests organized
It’s important for teams to employ a logical and scalable organizational framework for their API test suite—especially as the API grows and changes. For instance, teams should tag each test according to its purpose, which makes it easier to execute batches of related tests with a single command. They should also create distinct test suites for each API resource—and keep unit tests separate from end-to-end tests. Staying organized will help ensure that test logic is not duplicated, that outdated tests are removed, and that new engineers are able to onboard as quickly as possible.
Mock servers
Mock servers enable you to see exactly how your API will run—even before it’s in production. Create mock servers in Postman to simulate API endpoints when you don’t want to (or can’t) send API requests to a real API. You can also simulate network latency in your mock server by specifying custom delays for responses.
Mock servers are hosted on Postman’s cloud, which means they’re available wherever you need them—whether in your local, testing, or staging environments.
API design
You can design your API specifications in Postman using OpenAPI, RAML, GraphQL, or SOAP formats. Postman’s schema editor makes it easy to work with specification files of any size, and it validates specifications with a built-in linting engine. You can also generate Postman Collections for multiple stages of your API lifecycle—for mocks, documentation, tests, monitors, and more—all from the specification file, all in sync.
A Step-by-step Guide to Test API With Apidog
Test scenarios are used to run multiple APIs together in an orderly manner to test a complete business process.
StepSign Up for an Apidog Account
Go to the Apidog website and sign up for a free account or connect to your Google and Github.
StepCreate and Configure Your API
Click on the “+” button or”New API” and enter your API URL.
StepCreate a New Test Scenario
Click “Testing” in the left menu bar, click the button in the upper left corner, select the directory to which it belongs and set the priority to complete the creation.
StepAdd a Testing Step Or Import from the APIs
After entering the test scenario, click “Add Step” and add an API.
StepRun Your Test and View Your Test Results
Click on the “Run” button to run your test. Apidog will send requests to your API and run your test script to check for errors. After your test has finished, click on the “Results” tab to view your test results.
Apart from the steps discussed above, Apidog provides additional features to enhance API testing, including test data management and CI/CD integration.
1. Test data management: Apidog’s feature enables you to manage test data effectively and configure data sets for various test cases. It allows you to simulate different scenarios and ensure your API can handle various use cases. You can create different data sets for each test case, ensuring that your API functions correctly for all possible use cases.
2. CI/CD integration: Apidog can be easily integrated with widely used CI/CD tools such as Jenkins and GitLab. It allows you to automate your testing process and ensure that your API is thoroughly tested before deployment to production. You can ensure any issues are caught before they reach production by automatically running your test cases every time a new code change is pushed to your API.
Postman Online Version Usage Tips
By accessing the Postman online version, developers can conveniently test APIs anytime without the need to download and install the desktop application. When creating requests in the online version of Postman, you have access to a variety of powerful features that enhance your request management, testing, and overall workflow efficiency.
Some of these features include:
- Parameterization: Postman allows you to parameterize your requests, enabling you to dynamically change values such as endpoints, headers, and request bodies. This is particularly useful when you need to test different scenarios or iterate through a set of data.
- Environment Variables: You can define and utilize environment variables in Postman. These variables allow you to store and reuse values across multiple requests, making managing dynamic data easier and simplifying your testing process.
- Scripting: Postman supports script writing using JavaScript. You can add pre-request scripts, test scripts, and even write custom scripts to manipulate and validate request and response data. This gives you the flexibility to automate tasks, perform complex validations, and extract data for further processing.
- Multiple Data Formats: Postman online version supports various data formats, including JSON, XML, HTML, and more. This ensures comprehensive and accurate testing, allowing you to send requests and analyze responses in the desired format.
Các thành phần chính của Postman
Settings: chứa các thông tin về cài đặt chung.
- Thông tin Account: dùng để Login, logout và sync data.
- Settings tùy chỉnh: themes, shortcut, format…
- Import data từ ngoài vào
Collections: Lưu trữ thông tin của các API theo folder hoặc theo thời gian.
API content: Hiển thị nội dung chi tiết API và các phần hỗ trợ giúp thực hiện test API. Đây là phần mà tester phải làm việc nhiều nhất.
Trong phần này gồm có 3 thành phần chính:
- Enviroments: Chứa các thông tin môi trường.
- Request: Phần chứa các thông tin chính của API. (URL, Method, Headers và Body)
- Reponse: Chứa các thông tin trả về sau khi Send Request.
Ví dụ
Khi làm việc với API, chúng ta chỉ làm việc với 2 dạng API chính là GET và POST.
– GET: Yêu cầu server đưa lại resource:Có thể hình dung hi bạn vào facebook, hay vuốt new feeds. – POST: Yêu cầu server cho tạo ra 1 resource mới. Sau đây mình sẽ trình cách cách tạo request với phương thức GET và POST với ví dụ cụ thể
How to Create and Test API Using Postman Online
StepLog in to the Postman online version
Log in to the Postman account by clicking the “Sign in” button. If you do not have an account, click the “Sign up for free” button and follow the steps to create a new account.
StepCreate a New API
To create a new request, click on the “New” button and select the type of request you want to create (e.g., GET, POST, PUT, DELETE).
StepFill in the Request Basic Parameters
Enter the URL of the API endpoint you want to send the request to. You can also include any necessary parameters or headers.
StepSend the Request for Testing
Once you have filled in the required information, click on the “Send” button to send the request for API testing.
StepView the Request Response
Postman will send the request to the specified URL, and you will be able to view the response in Postman API. The response will include the status code, headers, and body of the API response.
Conclusion
Apidog is a feature-rich alternative to Postman that offers developers a more comprehensive API testing experience. Its advanced capabilities include creating custom test cases, generating reports, and performing load testing, which provides developers with more flexibility and power in their testing workflows. With its advanced features, Apidog provides developers with a more comprehensive and powerful testing solution than Postman.
Therefore, if you’re looking for a tool that offers greater flexibility, power, and collaboration capabilities, Apidog is undoubtedly worth considering as a replacement for Postman.
Hướng dẫn sử dụng Postman cho test API
Postman là gì?
Postman là một App Extensions, cho phép làm việc với các API, nhất là REST, giúp ích rất nhiều cho việc testing. Hỗ trợ tất cả các phương thức HTTP (GET, POST, PUT, DELETE, OPTIONS, HEAD …) Postman cho phép lưu lại các lần sử dụng. Sử dụng cho cá nhân hoặc team lớn.
Cài đặt
Là một công cụ mã nguồn mở (Open Source), Postman có thể dễ dàng tải về. Truy cậo trang chủ link và chọn nền tảng muốn cài đặt như cho Mac, Windows hoặc Linux rồi tiến hành cài đặt.
Cách sử dụng
Postman Online Free Alternative Tool: Apidog Online
Apidog Online is an alternative tool to Postman Online for API testing and documentation. Like Postman, Apidog offers a visual interface and a range of features to assist developers in testing and managing APIs.
Main Features of Apidog:
- API Testing: Apidog allows you to easily create and send HTTP requests to test your APIs. You can specify request headers, parameters, and bodies, and view the responses in real-time.
- Documentation Generation: With Apidog, you can generate interactive API documentation based on your API endpoints. This documentation includes details such as request/response examples, parameters, headers, and authentication requirements.
- Mock Server: Apidog provides a mock server functionality, allowing you to simulate API responses during the development or testing phases. This is useful when the actual API endpoints are not available or when you want to test specific scenarios.
- Collaboration and Teamwork: Apidog offers collaboration features, allowing multiple team members to work together on API projects. You can share API documentation, collaborate on testing, and manage access rights for different team members.
- Customizable Workflows: Apidog provides flexibility in defining custom workflows for API testing. You can create sequences of requests and set dependencies between them to simulate complex scenarios and ensure comprehensive testing coverage.
Tạo request POST
Tương tự như phần GET, chỉ khác là chúng ta cần điền thêm tham số vào trong body.
Trên đây là một số thông tin cơ bản về API Testing có sử dụng Postman. Mong rằng có thể giúp ích gì đó cho mọi người.
Tham khảo thêm :
[1] https://www.qasymphony.com/blog/automated-api-testing-tutorial/
[2] https://automationrhapsody.com/introduction-postman-examples/
All rights reserved
How To Automate API Testing With Postman
One of my favorite features in Postman is the ability to write automated tests for my APIs. So if you are like me and you use Postman and you are tired of manually testing your APIs, this article will show how to harness the test automation feature provided by Postman.
In case you don’t know what Postman is or you are entirely new to Postman, I will recommend you check out the Postman getting started documentation page and then come back to this article to learn how to automate testing your API with Postman.
APIs or Web APIs pretty much drive most of the user-facing digital products. With that said, as a backend or front-end developer being able to test these APIs with ease and more efficiently will allow you to move quickly in your development lifecycle.
Postman allows you to manually test your APIs in both its desktop and web-based applications. However, it also has the ability for you to automate these tests by writing JavaScript assertions on your API endpoints.
How to Create a Collection in Postman
To create a collection in the Postman online version, follow these steps:
- Click on the “New” button located in the top left corner of the page.
- Select “Collection” from the options that appear.
3. Provide a name for your collection and click on the “Create” button. Click on it to create it successfully and the new group and request will be listed under the collection in the sidebar.
4. You can also import collections by clicking the “Import” button in the upper right corner of the page. This makes it easy to share collections with other team members or back up your own collections.
5. Requests can be added to the collection by clicking the “Add a Request” button on the right side of the page.
Postman API Testing Tool
Postman is a comprehensive API testing tool that simplifies creating, testing, and documenting APIs. It provides an intuitive user interface that enables developers to design and test APIs and automate their testing processes easily. Postman also supports collaboration among team members by allowing them to share and version control their API tests and collections.
Why Use Postman for API Testing?
API testing is crucial for ensuring reliability and preserving consumer trust. It’s early issue detection and automation conserve resources, allowing teams to focus on innovation. Integration with CI/CD pipelines enables rapid iteration and frequent releases with reduced bug risks.
Postman is a popular tool for API testing that allows developers to create and execute HTTP requests and test API responses. Postman makes API testing more efficient and effective with features such as request builders, response visualizations, and test automation.
Vì sao phải test API?
-
Trong quá trình triển khai dự án, phần server và client làm độc lập với nhau nên có nhiều chỗ client chưa làm xong, mình không thể chờ client làm xong để test được dữ liệu mà test API bằng công cụ khác luôn –> Lúc này việc test hoàn toàn không phụ thuộc gì vào client.
-
Kể cả khi client làm xong rồi, nếu mình test trên client mà thấy lỗi liên quan đến logic và dữ liệu thì cũng cần test thêm cả API để biết chính xác là server sai hay client sai –> fix lỗi sẽ nhanh hơn.
-
Khi làm hệ thống web services, dự án của mình chỉ viết API cho bên khác dùng, mình sẽ không có client để test giống như các dự án khác –> phải test API hoàn toàn.
II.Postman
What is API testing?
API testing is the process of confirming that an API is working as expected. Developers can run API tests manually, or they can automate them with an API testing tool. There are several types of API tests, and each one plays a distinct role in ensuring the API remains reliable.
Traditionally, API testing has occurred at the end of the development phase, but an increasing number of teams are running tests earlier in the API lifecycle. This approach to API testing, which is known as “shifting left,” supports rapid iteration by enabling teams to catch and fix issues as soon as they are introduced.
Here, we’ll discuss the role that API testing plays in an API-first world—and clarify the relationship between API testing and API monitoring. We’ll also review some of the most common approaches to API testing, as well as some best practices. Finally, we’ll discuss how the Postman API Platform enables teams to implement an effective API testing strategy that meets their unique needs.
API testing
Build and run tests directly in Postman or as part of your CI/CD pipeline through Newman (a Collection Runner that enables you to run and test a Postman Collection directly from the command line). Postman can be used to write functional tests, integration tests, regression tests, and more. Postman’s Node.js-based runtime contains support for common patterns and libraries that you can use to build tests quickly.
Tạo request GET
Chúng ta sẽ dùng luôn API mẫu sẵn có mà Postman đã cung cấp
- URL: https://postman-echo.com/get
- Method: GET
- Headers: Không cần điền gì cả
- Body: Phương thức GET không có body, nhưng cần phải điền tham số vào Params
Dưới đây mình điền với key là test và value là 12345:
Sau khi điền đầy đủ thông tin thì ấn SEND để gửi request và chờ response trả về.
Thông tin trả về cần quan tâm:
-
Định dạng dữ liệu trả về: thông thường là json và nên để chế độ Pretty để cho dễ nhìn.
-
Nội dung dữ liệu: Đây là phần cần phải kiểm tra. – Bạn so sánh với cái Sample Response ở API docs để xem cấu trúc trả về đã đúng hay chưa. – Value của từng key đã đúng chưa, so sánh với nội dung trong DB. (không có DB là ko làm được API testing).
-
Trạng thái của API (status) và thời gian trả về. Thời gian chạy API bằng Postman luôn ngắn hơn thời gian test trên giao diện Mobile vì nhiều lý do: đường truyền internet ở máy tính ổn định hơn wifi, và sau khi nhận response thì Mobile phải chạy code khởi tạo giao diện để hiển thị.
Why You Should Automate API Tests
Testing in software development is used to ascertain the quality of any piece of software. If you are building APIs as a backend for a single frontend application or you are building APIs to be consumed by several services and clients, it’s important that the APIs work as expected.
Setting up automated API tests to test the different endpoints in your API will help catch bugs as quickly as possible.
It will also allow you to move quickly and add new features because you can simply run the test cases to see if you break anything along the way.
Postman’s annual user conference
Gain new skills through hands-on workshops, hear from industry leaders, and join conversations about innovation, APIs, and the future of software.
Learning Center
Learn about how to get started using Postman, and read more in the product docs.
Labs
Flows, gRPC, WebSockets! Learn about the latest cutting-edge features brewing in Postman Labs.
Open Technologies
Invest in the knowledge, specifications, standards, tooling, data, people, and organizations that define the next 50 years of the API economy.
Collection Format
Understand the specification behind Postman Collections. Check out the docs and support resources!
Blog
The Postman blog is your hub for API resources, news, and community. Learn about the Postman API Platform and much more.
Last modified: 2024/02/12
About ReqBin REST & SOAP Online API Testing Tool
ReqBin is an easy-to-use and user-friendly online API testing tool designed specifically for testing websites, web services, and REST and SOAP APIs. With ReqBin, you can quickly test API endpoints, view and validate server responses, save your requests in the cloud and share them online with colleagues, or add links to them in the documentation.
- Test APIs, websites and web services online.
- Post requests directly from your browser without installing any additional software on your computer.
- Accurate Timing: ReqBin API Tester shows the execution time of API requests to the millisecond, allowing you to identify performance bottlenecks and areas for optimizing your requests by reducing response times and latency.
- Validate server responses with built-in JSON, XML, HTML, and CSS validators. Verify that the returned data matches the specified format and contains no errors.
- Share and Collaborate: Share a link to your API requests with colleagues or stakeholders, or place links to them in your documentation. Start discussions about your requests to get feedback and ideas, and collaborate with other developers.
- Generate PHP, Python, JavaScript/AJAX, Java, C#/.NET, and Curl/Bash code snippets from your requests with just one click and speed up your development process.
- It’s safe: you don’t need to install browser plugins or software on your computer. Enter your request details and click “Send” to make the request and see the result. All data is transmitted only via secure SSL channels.
- It’s free: ReqBin Online API Tester is free to use. You can start running requests for free right now, at no additional cost.
ReqBin API test nodes are located in the US and EU, which you can use to compare API performance metrics for users across geographic regions.
What is API?
API (Application Programming Interface) is a computing interface that defines how software components interact with each other. It is a way of programmatically interacting with a separate software component or resource and expose functionality for internal or external use and testing. API defines what requests can be made, how they will be made and hides complexity from developers. API extends systems to partners, organizes code, and makes components reusable.
What is API testing?
API testing is a set of quality assurance actions that include making calls to an API endpoint, getting API responses, and validating API status codes, response times, and data against predefined rules. API testing is usually performed by a software tool or web service and mainly focuses on testing the business logic layer.
Why is API Testing Important?
API testing determines whether the API meets expectations for functionality, reliability, performance, and security. API testing is essential for the entire development, implementation and maintenance of APIs. API testing is necessary to accompany the API to make it functional and ready for its purpose.
How do I Test API Online?
You can test API online by composing and executing various API requests right from your browser. To test API online:1. Enter the URL of the API endpoint and select the appropriate HTTP method.2. In the Content tab, enter the data you want to send to the API endpoint.3. If your API server requires authorization, enter your credentials in the Authorization tab.4. Click Send to submit your API request, check the returned API status code, response time, and content.5. Re-run the API tests by changing the API endpoint URL, HTTP method, and request data.
Test API with Online REST API Client
ReqBin is the most popular Online REST API testing tool. You can quickly and easily test your API by sending API requests to REST API endpoints directly from your browser. ReqBin API Tester provides millisecond accurate timings for API requests and server responses. With the ReqBin load testing tool, you can test the API against hundreds of simulated concurrent users from different geographic regions.The REST API client works right in your browser. No coding. No desktop app. Fully online.
JSON and XML API Tester
Easily inspect returned JSON and XML responses. The built-in JSON and XML formatters automatically format and validate the returned data and highlight any errors in JSON and XML.
REST API Examples
Learn REST API best practices by browsing a collection of real-world REST API examples.
Postman Tutorial: How to Use Postman Online for API Testing
This post will explore the convenience of the Postman Online Version and learn how to test API using it step by step.
Postman is a widely popular and powerful API testing tool. It has gained extensive popularity for its ability to assist developers in quickly testing APIs. It offers a rich set of features such as request creation, script writing, and test result analysis. In the current development process, Postman has become an essential tool for many developers.
In addition to the desktop application, Postman also provides an online version that can be accessed through any web browser. So, how can you use the online version of Postman?
How to check if an API is up or down
How can we check if API is up or down in Pega 8.5.6 in Pega cloud.
API endpoint URL – https://hostname/prweb/api/ApplicationAPI/Work/CreateNewFlow
To see attachments, please log in.***Edited by Moderator Marije to add Capability tags***
***Edited by Moderator Marije to add Capability tags***
Basics of API Testing Using Postman
APIs(Application Programming Interfaces) are very commonly used in development. Postman is a tool that can be used for API Testing. In this article, we will learn how to do simple API Testing using Postman.
- Go to your workspace in Postman.
- Click on the + symbol to open a new tab.
- Enter the API Endpoint where it says, “Enter request URL” and select the method (action type GET, POST, etc.) for that request as shown below.
- Click on the Send button.
Now as you can see in the tab below, the response received from the API is shown along with the status 200 which implies that the request has succeeded.
For a post method, you can also specify the body of the request in any of the formats listed.
- Select method as POST and write the request URL.
- In this example, we will be sending request data in JSON format. For this, Go to Body and select raw from the radio buttons listed. Then, select JSON.
- Write the request body(you can also enter headers if required) and hit Send.
As you can see in the image above, status 201 is received implying that the request was successful and the resource has been created. More information related to the API call can be found under the “Headers”. You can also save the request by clicking on the save button and adding it to a collection in Postman.
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
Last Updated :
18 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment…
Tools
The Postman platform includes a comprehensive set of tools that help accelerate the API lifecycle—from design, testing, documentation, and mocking to the sharing and discoverability of your APIs.
Làm việc với request get
Request GET được sử dụng để truy vấn thông tin được truyền vào từ URL. Điều này sẽ không làm thay đổi gì với endpoint. Chúng ta sẽ sử dụng URL bên dưới cho các ví dụ trong bài này:
Trong workspace
- Thiết lập request HTTP của bạn là GET
- Trong trường URL yêu cầu, nhập vào link
- Kích nút Send
- Bạn sẽ nhìn thấy message là 200 ok
- Sẽ hiển thị kết quả 10 người dùng trong phần Body của bạn.
- Chú ý: Có thể có nhiều trường hợp request GET không thành công. Nó có thể là do URL của request không hợp lệ hoặc do chứng thực không thành công(authentication).
Hướng dẫn pass authentication
Như các bạn cũng biết, khi sử dụng một ứng dụng nào đó thì chúng ta hay phải tạo một tài khoản để có thể đăng nhập vào ứng dụng đó.
Khi vào một trang web bán hàng chẳng hạn, khi bạn muốn thực hiện chức năng thêm vào giỏ hàng thì yêu cầu bạn phải đăng nhập mới có thể thực hiện chức năng đó. Đúng vậy có những chắc năng mà bạn phải đăng nhập mới có thể thưc hiện được.
Để có thể test một chức năng trên postman mà yêu cầu bạn phải đăng nhập thì postman cho phép bạn truyền lên header của nó một biến Authorization có value là dạng chuối mã hóa Base64. Giá trị này chính là giá trị access_token của user khi user đó đăng nhập vào hệ thống.
Thực hiện: Chuyến đến tab header, thêm key Authorization và giá trị access_token của user đang đăng nhập.
Hướng dẫn pass basic authen
Phân biệt Authorization và Authentication
Authentication và Authorization hai khái niệm này liên quan chặt chẽ đến nhau. Trong khi Authentication cho phép hệ thống biết bạn là ai thì Authorization là quá trình cho phép hoặc từ chối ai đó truy cập vào một cái gì khi mà Authentication được thực hiện.
Chắc hẳn khi làm việc trong các dự án, khi các bạn test trên môi trường staging có lẽ đã gặp trường hợp phải pass qua basic authen.
Basic Access Authentication(Xác thực truy cập cơ bản) là loại đơn giản và cơ bản nhất hiện có. Nó chỉ kiểm tra ủy quyền của 1 người nào đó (đó là lí do tại sao chúng ta gọi xác thực truy cập cơ bản).
Hướng dẫn pass basic authen trong postman
Sử dụng endpoint: https://postman-echo.com/basic-auth với GET request
Tạo một request GET với endpoint: https://postman-echo.com/basic-auth và nhấn nút create ta sẽ thấy trả về Unauthorized.
Bây giờ chúng ta sẽ xác thực bằng mã hóa postman.
Chọn tab Authorization và click Basic Auth
Nhập username là postman và pasword là pasword sau đó click Preview Request. Sau đó click Send. Bạn sẽ thấy kết quả trả về “authenticated”: true Vậy là chúng ta đã pass basic authen trong postman.
Steps To Automating API Tests
When writing API tests in Postman, I normally take a four step approach:
- Manually testing the API;
- Understand the response returned by the API;
- Write the automated test;
- Repeat for each endpoint on the API.
For this article, I have a NodeJS web service powered by SailsJS that expose the following endpoints for:
- — the home of the API.
-
/user/signup
— Signs up a new user. -
/user/signin
— Signs in an exiting user. -
/listing/new
— Creates a new listing(a listing is details of a property owned by the user) for an existing user.
I have created and organized the endpoints for the demo service that we will be using in this article in a Postman collection so you can quickly import the collection and follow along.
Now let’s follow my four steps to automating API tests in Postman.
Test The API Manually
I will open Postman and switch over to a workspace I created called
demo
which has the
postman-test-demo-service
collection. You will also have access to the collection if you imported it from above. So my postman would look like this:
Our first test is to test the home endpoint() of the API. So I would open the request on the sidebar called
home
you can see it’s a Get request and by simply pressing Enter, I would send a GET request to the web service to see what it responds with. The image below shows that response:
Understand The Response Returned By The API
If you are following along and also from the screenshot above you will see the response came back with a status code of
200 OK
and also a JSON body with a
message
property with the value of
You have reached postman test demo web service
Knowing this is the expected response of the endpoint on our service, we can proceed to step 3 — writing the actual automated test.
Write The Automated Test
Postman comes out of the box with a powerful runtime based on Node.js which gives it’s users the ability to write scripts in the JavaScript language.
In Postman, you add scripts to be executed during two events in the Postman workflow:
- Before you make a request.These scripts are called pre-request script and you can write them under the Pre-request Script tab.
- After you’ve received a response from the request you made.These scripts are called Test scripts and it is this set of scripts that are our focus in this article. You write test scripts under the Tests tab in a Postman request.
The image below shows the Tests tab opened in Postman:
If you look to your right in the already opened request Tests tab, you will notice a list of snippets available to quickly get you started writing tests. Most of the time, these snippets are sufficient for quite a number of test scenarios. So I would select the snippet title
Status code: Code is 200
. This will generate the code below in the
Tests
editor:
pm.test("Status code is 200", function () { pm.response.to.have.status(200); });
Here is also how Postman would look like after clicking on that test snippet:
If you’ve written any form of tests in JavaScript using some of the testing frameworks out there like Jest, then the snippet above will seem familiar. But let me explain: All postman test suits or scenario begins with test() function which is exposed in the pm(short for Postman) global object provided by Postman for you. The
test
method takes two arguments: the first is the test description which in our test suite above reads:
Status code is 200
, the second argument is a callback function. It’s in this function you make your assertions or verification of the response on the particular request being tested.
You will notice we have a single assertion right now but you can have as many as you want. However, I like keeping assertions in separate tests most of the time.
Our assertion above simply asks Postman if the response return has a status code of 200. You could see how it reads like English. This is intentional in order to allow anyone to write these tests with ease.
Running Our Test
To run our test we will send a request to the endpoint again. Only this time around, when Postman receives the response from that request, it will run your tests. Below is an image showing the passing test in Postman (You can access test result on the Test Results tab of the response section in postman):
So our test passed! However, it’s crucial that we make our test scenario fail first, and then make it pass; this will help make sure that the scenario you are testing is not affected by any external factor, and that the test passes for the reason you are expecting it to pass — not something else. A good test should be predictable and the end result should be known beforehand.
To make our test pass, I will make a typo in the URL we are currently sending the GET request to. This will lead to a 404 Not Found status code which will make our test fail. Let’s do this. In the address bar currently having the variable of our baseUrl, I will add
/a
to it (it could be anything random actually). Making the request again and our test will fail like seen below:
Removing the string
/a
will make the test pass again.
We have written an automated test for the home route of our demo web service. At the moment we have a test case checking the status of the response. Let’s write another test case checking if the response body contains a
message
property as we have seen in the response and the value is ‘You have reached postman test demo web service’. Add the below code snippet to the test editor:
pm.test("Contains a message property", function() { let jsonData = pm.response.json(); pm.expect(jsonData.message).to.eql("You have reached postman test demo web service"); })
Your Postman window should look like this:
In the snippet above, we are creating a test case and getting the JavaScript object equivalent of the response body of the request which is originally in JSON by calling
json()
on it. Then we use the expect assertion method to check if the message property has a value of “You have reached postman test demo web service.”
Repeat!
I believe from the above first iteration of our 4 steps to writing API tests that you’ve seen the flow. So we would be repeating this flow to test all requests in the demo web service. Next up is the signup request. Let’s test on!
Postman’s annual user conference
Gain new skills through hands-on workshops, hear from industry leaders, and join conversations about innovation, APIs, and the future of software.
Postman Tutorial: How to Use Postman for API Testing
Postman is a powerful tool that can help you test your API. Check this article to learn how to test your API with Postman.
Do you want to ensure that your API is functioning as expected? Postman is a powerful tool that can help you proceed with API testing by sending GET, POST, PUT, and DELETE requests, receiving responses, and validating the results. Postman imposes limitations with only 5 free flows for users and a restricted collection of runners.
Validation Examples
Validating Response Status Code
-
Validate single status code:
pm.test("the endpoint returns the expected status code", () => { // change 200 to the response code you expect const expectedStatusCode = 200; pm.response.to.have.status(expectedStatusCode); });
-
Validate multiple status codes:
// change 200 or 201 to the response code you expect pm.test("Status code is 200 or 201", function () { pm.expect(pm.response.code).to.be.oneOf([200, 201]); });
Validating Response Time
// change 500 to the expected response time pm.test("Response time is less than 500ms", function () { pm.expect(pm.response.responseTime).to.be.below(500); });
Validating Response Headers
pm.test("Content-Type is application/json", function () { pm.response.to.have.header("Content-Type", "application/json"); });
Validating Response Body
Postman test to check field value in response
We can validate the value of both
id
and
name
fields of the
https://rickandmortyapi.com/api/character/1
using the test below.
pm.test("API response contains the expected fields", () => { const response = pm.response.json(); // the line below checks value of the id field is 1 (number). pm.expect(response).to.have.property("id", 1); // the line below checks value of the name field is Rick Sanchez (string). pm.expect(response).to.have.property("name", "Rick Sanchez"); });
Test if Response Body matches schema
Testing if the response body matches a specific schema
pm.test("Body matches schema", function () { let schema = { type: "object", properties: { id: { type: "integer" }, name: { type: "string" }, status: { type: "string" }, species: { type: "string" }, type: { type: "string" }, gender: { type: "string" }, origin: { type: "object", properties: { name: { type: "string" }, url: { type: "string" }, }, required: ["name", "url"], // Added required property for origin }, location: { type: "object", properties: { name: { type: "string" }, url: { type: "string" }, }, required: ["name", "url"], // Added required property for location }, image: { type: "string" }, episode: { type: "array", items: { type: "string" }, }, url: { type: "string" }, created: { type: "string" }, }, required: [ "id", "name", "status", "species", "type", "gender", "origin", "location", "image", "episode", "url", "created", ], }; pm.expect(pm.response.json()).to.be.jsonSchema(schema); });
Test if nested field value is available in response
The script below step works for fields at the root of the response. What if we wanted to test the name field under the origin field. We can tweak the script to support fields at any level.
pm.test("API response contains the expected fields", () => { const response = pm.response.json(); // the line below checks value of the id field is 1 (number). pm.expect(response).to.have.nested.property("id", 1); // the line below checks value of the name field is Rick Sanchez (string). pm.expect(response).to.have.nested.property("name", "Rick Sanchez"); // the line below checks value of the origin.name field is Earth (C-137) (string). pm.expect(response).to.have.nested.property("origin.name", "Earth (C-137)"); });
Check nested array value in response
We can take it further and use the same technique to validate the value of items in the array. For example, we can use the script below to check the value of the second item in the episode array of the https://rickandmortyapi.com/api/character/1 endpoint.
pm.test("API response contains the expected fields", () => { const response = pm.response.json(); // the line below checks the value of the episode field at index 0 is "https://rickandmortyapi.com/api/episode/1". pm.expect(response).to.have.nested.property("episode.0", "https://rickandmortyapi.com/api/episode/1"); });
Các thiết lập các tham số Request
Tham số hóa dữ liệu là một trong những tính năng hữu ích nhất của Postman. Để tạo cùng một request với dữ liệu khác nhau, bạn có thể sử dụng các biến với tham số. Những dữ liệu này có thể từ một tệp dữ liệu hoặc biến môi trường. Tham số hóa giúp tránh lặp lại các thử nghiệm tương tự và có thể sử dụng để kiểm thử tự động.
Các tham số được tạo thông qua việc sử dụng dấu ngoặc kép: {{sample}}. Chúng ta hãy xem một ví dụ về việc sử dụng các tham số trong request trước đây
Bây giờ hãy tạo một tham số cho request
Bươc 1:
- Thiết lập request HTTP là GET
- Nhập vào 1 link: https://jsonplaceholder.typicode.com/users. Thay thế phần đầu tiên của link bằng một biến như {{url}}. URL request lúc này sẽ là {{url}}/users.
- Kích nút Send
Không nhận đựoc giá trị nào vì chúng ta chưa đặt giá trị cho biến này.
Bước 2: Để sử dụng biến này bạn cần thiết lập môi trường
- Kích vào biểu tượng mắt
- Kích Edit để thiết lập biết cho sử dụng toàn cục mà sẽ được sử dụng trong tất cả các collection
Bước 3:
- Thiết lập tên url: https://jsonplaceholder.typicode.com
- Kích nút Save
Bước 4: Kích Close nếu bạn muốn đóng màn hình này
Bước 5: Trở lại request GET và kích nút Send. Bạn sẽ nhìn thấy kết quả của bạn
Signin Request
The signin request’s response body is similar to the signup request. You could verify that by hitting the endpoint with user credentials – emailAddress and Password – you signed up already. After you have done that, add the following test cases to the tests editor:
pm.test("Status code is 200", function () { pm.response.to.have.status(200); }); pm.test("Response has a JSON body", function () { pm.response.to.be.json; }); pm.test("Response has a token property", function () { var jsonData = pm.response.json(); pm.expect(jsonData.token).to.be.a('string'); }); pm.test("Response has a data property", function () { var jsonData = pm.response.json(); pm.expect(jsonData.data).to.be.a('object'); });
Make the request to signin with a valid user credential and your test should pass and Postman should look like so:
Finally, we would be testing the
listing/new
endpoint of our demo API.
Why is API testing important in an API-first world?
Today’s software landscape is highly competitive, and users are increasingly unwilling to tolerate unreliable applications. An issue at an application’s API layer can lead to user-facing errors or latency, which can erode customer trust, lead to churn, and negatively impact the business. This puts enormous pressure on development teams to deliver APIs that are consistently available and highly performant.
Many teams have chosen to tackle this challenge by adopting the API-first development model, in which applications are conceptualized and built as a collection of internal and external services that are delivered through APIs. This strategy treats APIs as crucial infrastructure components, which makes API quality a top priority. API testing plays a central role in the API-first approach, as it enables teams to continuously verify the quality, health, and performance of their endpoints as they work to deliver a seamless digital experience.
What is the relationship between API testing and API monitoring?
API testing and API monitoring share the goal of ensuring that APIs remain reliable and performant, but these processes are typically performed at different stages of the API lifecycle. API testing occurs during development, and its primary purpose is to help teams catch issues before they reach production and impact users. API monitoring may utilize this same testing logic, but it occurs after the API has been deployed to production. API monitoring also involves gathering and visualizing API telemetry data, which teams can use to perform historical analysis and surface long-term performance trends.
Why use Postman for API testing?
The Postman API Platform includes several API testing features that help teams streamline their testing workflows and catch issues throughout the API lifecycle. With Postman, you can:
- Test any API with pre-configured code snippets: Postman includes a JavaScript-based library of code snippets that enable teams to easily author tests that validate their API’s performance, reliability, and behavior. These snippets can be executed against a variety of API architectures, including REST, GraphQL, SOAP, and gRPC.
- Validate complex, end-to-end workflows: Teams can use Postman’s Collection Runner to chain requests together, execute them in specific sequences, and log test results. This enables teams to create test suites that validate the most sophisticated, business-critical user journeys.
- Automate test executions on Postman Cloud: With Postman, users can schedule test executions to occur at specified times and frequencies—and get notified when tests fail. These executions will run on Postman’s infrastructure, so teams don’t have to worry about failures that result from unavailable local resources.
- Execute API tests within CI/CD pipelines: Teams can use Newman or the Postman CLI to run collections and tests within their CI/CD pipeline. This helps ensure backwards compatibility by safeguarding the production environment from breaking changes.
- Monitor test results and troubleshoot bugs: Postman users can debug test failures with the Postman Console, which enables them to inspect every network call—including headers, certificates, requests, and responses. They can also monitor results from manual and automated runs—and access reports to identify testing trends.
- Create a dedicated testing environment: Postman lets users store values in variables at the environment level, which can be used in any request’s URL, headers, and body. This allows users to run automated API tests in a dedicated testing environment before deploying code to production.
- Incorporate Postman API tests into incident response workflows: Postman integrates with several third-party monitoring and incident response tools, such as Datadog, New Relic, and Opsgenie, which allows teams to augment their incident response workflows with Postman test data.
Using expect for Assertions
Introduction to Chai Library
Chai is a versatile assertion library used in JavaScript programming, especially for test-driven development (TDD) and behaviour-driven development (BDD). In the context of Postman for API testing, Chai offers a rich set of assertions that help validate the responses from API requests, ensuring that they meet the expected criteria.
Purpose of Assertion Libraries
An assertion library like Chai serves a fundamental role in testing:
- Verification: It provides a systematic way to check whether the output of a code block (or, in this case, an API response) matches the expected result.
- Readability: Chai’s syntax is designed to be human-readable, making tests easier to write and understand.
- Robust Testing: Covering a wide range of assertion types allows testers to write comprehensive tests covering various aspects of the API response.
Using expect in Postman
Within Postman, ‘expect’ statements allow you to perform detailed checks on your response data. For example:
pm.test("Response should be an object", function () { pm.expect(pm.response.json()).to.be.an("object"); });
Writing Tests in Postman
The “Tests” Tab
In Postman, the “Tests” tab is your hub for scripting tests. This tab, located within each request, allows you to write JavaScript tests that evaluate the response of your API.
Best Practices for Writing Tests
Following these best practices will make your Postman tests more practical and more convenient to handle and understand. This approach ensures a robust and reliable API testing process.:
1. Descriptive and Clear Test Names
- Why It’s Important: Clear names make it easier to understand what each test checks at a glance, especially when reviewing test results or sharing tests with colleagues.
- Example: Instead of naming a test “Test 1” or “Status Check,” use descriptive names like “Verify Status Code is 200 for User Endpoint” or “Ensure Response Time is Below 500ms.”
2. Testing One Concern Per Test
-
Why It’s Important: Focusing on one assertion per test simplifies troubleshooting and understanding test results. If a test fails, you know just what went wrong.
-
Example: Separate them instead of combining status code and response time checks in one test:
// Test for status code pm.test("Status code is 200", function () { pm.response.to.have.status(200); }); // Test for response time pm.test("Response time is less than 500ms", function () { pm.expect(pm.response.responseTime).to.be.below(500); }); ```
3. Use Assertive Language
- Why It’s Important: Assertive language in tests makes them more readable and intention-driven. It clarifies the purpose of the test.
-
Example: Use assertive phrases like
expect(response).to.contain...
or
response.should.have...
, clearly stating the test’s expectations.
4. Organize Tests Logically
- Why It’s Important: Grouping related tests or organizing them logically can make your testing suite more understandable and maintainable.
- Example: If testing various aspects of a user API, group tests related to user creation, user data retrieval, and user deletion together.
5. Handle Different Test Scenarios
-
Why It’s Important: Testing only the “happy path” can leave critical bugs in edge cases. It’s essential to test various scenarios, including potential error conditions.
-
Example: Alongside testing a successful API call, write tests for scenarios like invalid inputs, unauthorized access, or server errors.
// Test for invalid input pm.test("Response for invalid input is 400", function () { pm.expect(pm.response.code).to.eql(400); });
6. Maintainability and Reusability
- Why It’s Important: Tests should be easy to update and reusable for different scenarios. This practice saves time and effort in the long run.
- Example: Create reusable functions for common test assertions. Call these functions with different parameters as needed rather than writing the same code in multiple tests.
7. Commenting and Documentation
- Why It’s Important: Good comments and documentation make it easier for others (and your future self) to understand the purpose and mechanics of your tests.
- Example: Add comments to clarify complex logic or the reason behind specific test cases, especially when testing less obvious or intricate API parts.
Apidog Tutorial: How to Test API in Apidog Online?
Here is a step-by-step guide to tell you how to use Apidog for API testing easily.
Step 1. Log in to Apidog by Google or GitHub.
Step 2. Create a new API or request by clicking the “+” tab as well as the below “New API”.
Step 3. Set up the parameters, such as the request methods, and URL in Apidog visual interface. After filling in the basic information, you can click “Save” for convenience.
Step 4. Send the API with a simple click. For a second, it will respond the API testing result, and you can analyze it in Test Report.
It’s worth noting that Apidog online is just one of many alternative tools available in the API testing and documentation space. Here is also the Apidog desktop application. Depending on your specific requirements and preferences, you may explore multiple options and choose the one that best fits your needs.
Cách tạo colection
Collection đóng một vai trò quan trọng trong việc tổ chức các bộ thử nghiệm. Nó có thể được import và export để dễ dàng chia sẻ các collection giữa các nhóm. Trong hướng dẫn này, chúng ta sẽ tìm hiểu cách tạo và thực hiện một bộ sưu tập.
Bắt đầu tạo một collection:
Bước 1: Click vào nút New ở góc trái của trang:
Bước 2: Chọn Collection, Cửa sổ tạo Collection sẽ hiển thị ra:
Bước 3: Nhập vào tên Collection và mô tả. Sau đó nhấn nút Create, sau đó 1 collection sẽ được tạo ra:
Bước 4: Trở lại request GET lần trứoc và kích nút Save:
Bước 5:
- Chọn Postman Test Collection.
- Kích nút Save to Postman Test Collection
Bước 6: Postman test collection bấy giờ sẽ chứa một request
Bước 7: Lặp lại Bước 4-5 cho request POST phần trước. Collection bây giờ sẽ có hai request.
API client
The Postman API client is the foundational tool of Postman, and it enables you to easily explore, debug, and test your APIs while also enabling you to define complex API requests for HTTP, REST, SOAP, GraphQL, and WebSockets.
The API client automatically detects the language of the response, links, and format text inside the body to make inspection easy. The client also includes built-in support for authentication protocols like OAuth 1.2/2.0, AWS Signature, Hawk, and many more.
Through the API client, you can organize requests into Postman Collections to help you organize your requests for reuse so you don’t waste time building everything from scratch. Your collections can also contain JavaScript code to tie requests together or automate common workflows, and you can use scripting to visualize your API responses as charts and graphs.
Other common questions about API testing
What do you need to begin API testing?
In order to start testing an API, you’ll need the API’s specification or documentation, which will include detailed information about the available endpoints, parameters, and methods. You’ll also need a list of common use cases to capture in your test logic, as well as a testing environment that mirrors the production environment as closely as possible. Finally, you’ll need an API testing tool like Postman, which will simplify the testing process while supporting automation and collaboration.
How does API test automation fit in?
API test automation involves executing API tests at predetermined times or frequencies, or within CI/CD pipelines. It improves testing efficiency, reduces the risk of human errors, and enables teams to iterate rapidly and confidently.
What tools do you need for API testing?
The specific tools that you’ll need for API testing will depend on your API’s use case, architecture, and protocol. That being said, most teams will need an API client like Postman, a code editor like Visual Studio Code, and a collaboration tool like Jira.
How do you introduce API testing at your organization?
An organizational approach to API testing requires careful planning and iteration, and it cannot be successfully implemented overnight. You’ll need to start by identifying the stakeholders, goals, timelines, required resources, and expected outcomes. You’ll also need to choose the types of tests to be performed, as well as the tools to be used. Once your team has written tests and created a testing environment, it’s important to monitor the impact and identify opportunities for improvement.
Conclusion
This article aims at showing you how to utilize Postman to write automated tests for your APIs which will allow you to bridge the gap between development and quality assurance, and also minimize the surface area of bugs in your API.
Additional Resources
- Automated Testing With Postman (Official Postman website)
- “Snapshot Testing For APIs Using Postman,” Prashant Agrawal, Medium
- “From Manual To Automated Testing: The Roadblocks And The Journey,” Kaustav Das Modak, Medium
Postman is a tool to help you develop APIs. Postman helps you build APIs by providing tools to capture, validate, and test requests and responses. API testing is the process of verifying that your Application Programming Interface (API) is working correctly. This article will use Postman & Javascript for API testing.
Comparison Between Postman and Apidog
Postman and Apidog are popular API testing tools used for testing and monitoring APIs. While these two tools share several similar features and functionalities, they also have significant key differences.
Feature | Apidog | Postman |
Customizable Test Cases | Allows users to create custom test cases tailored to specific API requirements. Users can create complex test scenarios (including edge cases and error handling) to ensure thorough API testing. | Does not support the use of customizable test cases. |
Load Testing Capabilities | Supports high-traffic simulation, allowing users to monitor API performance under stress and identify potential and optimize bottlenecks for maximum throughput. | Does not offer performance testing capability. |
Open-Source | Supports open-source scripting languages like Python and JavaScript, making API testing customized and automated coding easier for developers. | Only supports Postman’s proprietary scripting language, which limits customization. |
Intuitive User Interface | Apidog has a more user-friendly and intuitive user interface, which makes it easier for users to create and manage collections and test cases. | Postman’s user interface can be more complex to navigate. |
Collaborative Features | Allows users to share collections and collaborate with team members in real-time while tracking and managing test results, making it easy for teams to work together. | Has limited collaboration features. |
Unlimited Test Runs | Allows for unlimited test runs of collections, making it more suitable for larger teams. | The collection runner has limited test runs that are restricted to the free plan. This can impose limits on larger teams. |
Pricing | Apidog is free. | Postman offers free and paid plans that provide advanced features. |
Robust Test Automation | Provides robust testing automation features (including assertions, scripts, and data-driven testing), allowing users to create complex test scenarios and automate API testing workflows effortlessly. | Provides limited test automation features that can be overly complex for executing straightforward tests. |
Làm việc với request post
Request post khác với request get ở chố request post có thao tác dữ liệu.
Bước 1: Kích dấu + để thêm mới một tab cho request mới:
Bước 2: Trong tab mới
- Thiết lập request HTTP là POST
- Nhập vào link với url: https://jsonplaceholder.typicode.com/users
- Chuyển tới tab Body
Bước 3: Trong tab Body
- Click chọn raw
- Select JSON
Bước 4: Copy và paste chỉ một user từ kết quả request trước như bên dưới. Đảm bảo rằng mã đã được sao chép chính xác với các dấu đóng mở. Thay đổi id thành 11 và đặt name bất kỳ tên nào bạn muốn. Bạn cũng có thể thay đổi các trường khác như address.
[ { "id": 11, "name": "Krishna Rungta", "username": "Bret", "email": "[email protected] ", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } } ]
- Chú ý: Request POST nên đúng định dạng để đảm bảo dữ liệu được yêu cầu sẽ được tạo. Kinh nghiệm để check dữ liệu JSON đúng định dang hay không, bạn có thể sử dụng tool như: https://jsonformatter.curiousconcept.com/
Bước 5:
- Kích nút Send
- Status: 201 Created được hiển thị
- Dữ liệu Post được hiển thị trong tab Body
Key Elements to Validate
- Status Code: Ensure your API returns the correct status code, indicating the request’s success or failure.
- Response Body: Validate the structure and data of the response body to ensure your API returns the expected data.
- Response Headers: Checking headers can verify content type, caching rules, and more.
- Response Time: Ensuring your API responds in a timely manner is crucial for performance.
Signup Request
The signup request is a POST request expecting the fullName, emailAddress, and password of a user. In postman, you can add these parameters in many ways however we would opt into
x-www-form-urlencoded
method in the Body tabs of the request section. The image below gives an example of the parameters:
Here is the response with the above request:
{ "message": "An account has been created for [email protected] successfully", "data": { "createdAt": 1596634791698, "updatedAt": 1596634791698, "id": "9fa2e648-1db5-4ea9-89a1-3be5bc73cb34", "emailAddress": "[email protected]", "fullName": "Kelvin Omereshone" }, "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJrZWx2aW5vbWVyZXNob25lQGdtYWlsLmNvbSIsImlzcyI6Ik15UGFkaSBCYWNrZW5kIiwiaWF0IjoxNTk2NjM0NzkxfQ.otCcXSmhP4mNWAHnrYvvzHkgU8yX8yRE5rcVtmGJ68k" }
From the above response body, you will notice a token property is returned with the response body. So we would write a test case to assert if a JSON response body was returned and if it contains the property
token
. Also, we would check for the status code as well which returns 201 Created. So open the Tests tab and add the following snippets:
pm.test("Status code is 201", function () { pm.response.to.have.status(201); }); pm.test("Response has a JSON body", function () { pm.response.to.be.json; }); pm.test("Response has a token property", function () { var jsonData = pm.response.json(); pm.expect(jsonData.token).to.be.a('string'); });
What each test case does should be obvious enough from the test description. From top to bottom, we check if the response is a 201 Created status code, we assert also if the response body is JSON and lastly we assert if the token property has a value of type string. Let’s run our tests.
Note: Make sure you change at least the email address of the new user as the Web service won’t allow for duplicate emails.
Our tests should pass and when you check the
Test Results
tab of the Response section you should get 3 passing tests as shown below:
Let’s move onward to testing the
signin
endpoint…
Keywords searched by users: postman online test api
Categories: Phổ biến 87 Postman Online Test Api
See more here: kientrucannam.vn
See more: https://kientrucannam.vn/vn/