title | order | updated | page_id | contextual_links | warning | ||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Receiving responses |
23 |
2022-01-27 |
responses |
|
false |
The Postman response viewer helps you to visualize and check the correctness of API responses. An API response consists of the response body, headers, and the HTTP status code.
Contents
- Response body
- Cookies
- Headers
- Test results
- Network information
- SSL verification errors
- Response code
- Response time
- Response size
- Saving responses
- Viewing security warnings
Response body
The Postman Body tab gives you several tools to help you understand the response quickly. You can view the body in one of four views: Pretty, Raw, Preview, and Visualize.
Finding items in responses — To open the search bar, select the search icon
in the results pane. You can also place your cursor in the response and select ⌘+F or Ctrl+F. This option isn’t available in a response’s Preview or Visualize views.
Note that if the response’s Content-Type
header indicates that the response is an image, Postman will detect and render the image automatically.
Pretty
The Pretty view formats JSON or XML responses so they’re easier to view. Links inside Pretty view are highlighted, and selecting them can load a GET request in Postman with the link URL.
For navigating large responses, select the down arrows next to a line to collapse large sections of the response.
Forcing JSON formatting. For Postman to automatically format the body, the response must have the appropriate
Content-Type
header. If you receive a response with a differentContent-Type
header, you can force formatting through JSON. In the Postman header, select the settings icon, then select Settings. In the General tab, select JSON from the Language detection dropdown.
Raw
The Raw view is a large text area with the response body. It can indicate whether your response is minified.
Preview
The Preview view renders the response in a sandboxed iframe. Some web frameworks by default return HTML errors, and Preview can be especially helpful for debugging in those cases.
Due to iframe sandbox restrictions, JavaScript and images are turned off in the iframe. For binary response types, you can select “Send and download” to save the response locally. You can then view it using the appropriate viewer. This gives you the flexibility to test audio files, PDFs, zip files, or any other file types the API returns.
Visualize
The Visualize view renders the data in the API response according to visualization code that you add to the requests Tests. For details on how to add, use, and debug visualization code, see Visualizing responses.
Cookies
You can inspect cookies sent by the server in the Cookies tab. A cookie’s entry includes its name, value, the associated domain and path, and other information about the cookie.
To learn more about working with cookies in Postman, see Using cookies.
Headers
Headers are displayed as key-value pairs under the Headers tab. Hover over the information icon next to the header name to get a description of the header according to the HTTP specification.
If you send a HEAD request, Postman will show the Headers tab by default instead of the Body tab.
Test results
If the API request you are viewing had any test scripts, the results are displayed in the Test Results tab.
To learn more about running tests against API requests in Postman, see Writing tests.
Network information
Postman displays network information when your API returns a response. Hover over the network icon to get the local and remote IP addresses for the request you sent.
When you make an https
request, the network icon includes a padlock. When you hover over the icon, the network information will show more information including certificate verification details.
SSL verification errors
If you have SSL verification enabled in Postman’s global settings and verification fails, the response area will display an error message. Select the link in the error message to turn off verification globally and immediately run the request again.
If SSL is turned off globally but turned on for your request, Postman displays the error and gives you a link to open the console.
If you select Disable SSL Verification in the error message, you will need to turn it back on if you want to verify certificates for future requests. To enable it globally, select the settings icon
in the header and then select Settings. In the General tab, select SSL certificate verification.
To enable SSL verification for only the current request, select the Settings tab in the request, and then select Enable SSL certificate verification.
If you have SSL verification turned off and your request returns a certificate verification error, you can hover over the network information for details about the error.
For requests that return data successfully but with a certificate verification failure, the console displays a warning.
Response code
Postman displays the response code returned by the API. Hover over the response code to get a short description of the code and what it means.
Some API responses also contain custom messages that can help you understand response codes. For example, if you receive a 401 Unauthorized
response, the message might tell you to check the token you used in the request. If custom messages are returned, they’re displayed in the Body of the response.
Response time
Postman automatically calculates the time in milliseconds it took for the response to arrive from the server. This information can be useful for some preliminary performance testing. Hover over the response time for a graph with information on how long each event in the process took.
Response size
Postman displays the approximate size of the response. Hover over the response size to get a breakdown by body and header sizes.
Saving responses
If a request has been saved in a collection, you can save responses for that request. Once the response has been returned, you can:
Viewing security warnings
Postman applies security rules configured for your API requests when you send requests to any API using either the Postman web app or the Postman desktop app. A security warning indicates that there are potential security risks the API might be vulnerable to, but they don’t mean the API is broken.
To view the specific security warnings that Postman applies to all requests, see Security warnings.
If it finds any potential security risks, Postman adds the number of warnings to the Security tab in the response.
To view the list of security warnings and to get more information about specific warnings, do the following:
- Select Security to view the warnings.
- For more details, select a warning to expand it.
- Select Possible fix to learn about possible ways to fix the underlying problem.
Hiding security warnings
To turn a warning off for the current API response, do the following:
- Select Hide warning.
- Choose a reason for hiding it, then select Hide.
This will turn the warning off for all members of your team, but only for this response.
To turn a warning off globally for your team, you can configure your API Security rules (available for Enterprise teams only).
When you or another member of your team has hidden a warning, Postman shows a message in the Security tab to indicate how many are hidden.
To turn this warning back on later, do the following:
- Select Review.
- Review your hidden warnings and select the eye icon
next to the one you want to turn back on.
Автор: Кристин Джеквони (Kristin Jackvony)
Оригинал статьи
Перевод: Ольга Алифанова.
Если вы хоть раз делали REST-запрос или изучали раздел инструментов разработчика в браузере, то наверняка видели код ответа из трех цифр, возвращенный в ответ на HTTP-запрос. Давайте поговорим о различных типах кодов ответа, которые можно получить в процессе тестирования API, и том, что они означают.
Ответы 100
Ответы уровня 100 означают, что запрос должен продолжаться. Наиболее частый тип такого ответа – это просто-напросто 100 Continue. Это может использоваться при объемных запросах, давая серверу возможность остановить большой запрос до того, как будет передан слишком большой объем данных. Возможно, при тестировании вашего API вы с этим не столкнетесь – сервер продолжит отвечать, завершит этот процесс «за кулисами» и выдаст ответ-200.
Ответы 200
Ответы уровня 200 обозначают успех запроса. Наиболее распространенный ответ – это 200 OK, который просто означает, что все прошло как ожидалось. Вот другие примеры запросов этого уровня:
201 Created – такой ответ означает, что в результате запроса создан некий новый ресурс. К примеру, GET-запрос может создать запись в логе, демонстрирующую дату, время и содержание запроса.
202 Accepted – этот ответ значит, что запрос был принят, но еще не завершен. Например, это изменение базы данных, которое нуждается в одобрении перед тем, как повлиять на базу непосредственно.
204 No Content – это значит, что запрос был успешно обработан, и не вернул никаких данных. Этот ответ может прийти на PUT-запрос, когда содержание изменилось, но разработчик не видел необходимости отдавать в ответе какие-то данные. Ответ 200 OK тоже может не возвращать данные, если так решил разработчик, но 204 не возвращает их никогда.
Ответы 300
Ответы уровня 300 говорят о перемещении ресурса. Наиболее частый из таких ответов – это 301 Moved Permanently. Этот ответ должен включать новый URL в заголовке, чтобы клиент понимал, куда в следующий раз обращаться с запросом.
Ответы 400
Ответы уровня 400 обозначают, что с запросом было что-то не так. Наиболее частый из них – 400 Bad Request, обычно применяемый, когда запрос неверно сформулирован или по какой-то причине неправилен. К примеру, в нем отсутствуют необходимые данные, или произошла ошибка валидации этих данных. Другие распространенные варианты ответов-400:
401 Unauthorized – обычно отдается, если у клиента нет соответствующей аутентификации для запроса, к примеру, токена JWT или куки.
403 Forbidden – отдается, если у клиента есть аутентификация, но нет прав на просмотр ресурса. К примеру, пользователь залогинен и может запрашивать свои данные, но не может запрашивать чужие.
404 Not Found – возвращается, если клиент запрашивает специфический ресурс, а сервер не может его найти. Например, запрашивается пользователь с ID 100, отсутствующий в базе данных.
409 Conflict – отдается, если запрос заставляет данные конфликтовать друг с другом. К примеру, клиент пытается осуществить POST-запрос для создания ресурса с ID, который уже используется.
Ответы 500
Ответы уровня 500 значат, что что-то пошло не так на серверной стороне. Чаще всего встречается ответ 500 Internal Server Error, использующийся для обозначения разнообразных проблем. Например, запрос пытался добавить запись в базу данных, которая не может обработать такую запись, потому что в ней слишком много символов, или у записи неверный тип. Другие ответы уровня 500 могут быть такими:
502 Bad Gateway – происходит, если сервер, отвечающий на запрос, должен сделать запрос к другому серверу, а другой сервер возвращает невалидный ответ.
503 Service Unavailable – такой ответ возвращается, если отвечающий сервер по какой-то причине недоступен. Он обычно более полезен, нежели общий ответ 500, потому что сигнализирует, что проблема с доступностью сервера, а не с базой.
Теперь, когда мы знаем, что значат коды ответов, давайте посмотрим на них предметно в нашей коллекции Postman PetStore! Если вы еще не создали, см. предыдущую статью. Кликните на первом запросе в коллекции: Add Pet. Под URL запроса нажмите на «тесты». В правой стороне окна будет список сниппетов кода, которые можно использовать для создания правил. Проскролльте список вниз, пока не найдете сниппет «Status code: Code is 200», и нажмите на него. Это автоматически добавит правило в поле теста, который выглядит вот так:
pm.test("Status code is 200", function () { pm.response.to.have.status(200); });
Секция «Status code is 200» – это название вашего теста. Секция «pm.response.to.have.status(200)» – это ожидаемый результат.
Нажмите кнопку «Save», а затем «Send». В нижней части страницы вы увидите секцию «Test Results» с «1/1» после названия секции. Это значит, что был запущен один тест, и один тест прошел успешно. Если нажать на ссылку «Test Results», вы увидите «PASS» и «Status code is 200» в секции ответа. Вы успешно добавили правило к вашему запросу!
Давайте посмотрим, как выглядит упавшее правило. Чтобы заставить его упасть, просто измените тело правила на:
pm.test("Status code is 202", function () { pm.response.to.have.status(202); });
Теперь мы ожидаем ответа 202, а не 200. Снова запустите запрос, и вы увидите «0/1» рядом со ссылкой «Test Results». Нажмите на ссылку, и в секции ответа вы увидите «FAIL» и «Status code is 202». Это значит, что тест по имени «Status code is 202» упал.
Снова поменяйте тест, чтобы он ожидал ответа 200, и добавьте правило ко всем запросам коллекции, кроме запроса «Verify Delete Pet». Этот запрос ищет запись, которая больше не существует, поэтому там мы не ожидаем ответа 200. Вместо этого мы должны получить 404 Not Found. Давайте добавим это ожидание в секцию тестов:
pm.test("Status code is 404", function () { pm.response.to.have.status(404); });
Нажмите на кнопку «Save» и сохраните тест.
Если вы прогоните этот запрос до запроса Delete Pet, то тест упадет, потому что животное с ID 100 все еще существует. Но если вначале запросить Delete Pet, а затем Verify Delete Pet, то тест будет пройден успешно, потому что животного с ID 100 больше нет в базе данных.
Теперь у нас есть правила для всех наших запросов. Давайте запустим прогон всей коллекции! Наведите курсор на название коллекции Pet Store, и нажмите на шеврон >, который появится справа. Кликните по кнопке «Run», и откроется Collection Runner. Нажмите на имя вашей коллекции, а затем – на кнопку «Run Pet Store». Вы увидите, как запускаются (и успешно выполняются) все ваши тесты, причем очень быстро! Окно результатов будет выглядеть примерно так:
В верхней части окна вы увидите, что шесть ваших тестов прошло успешно, и ни один не упал. Вы увидите названия всех созданных запросов, имена тестов для каждого запроса, и индикатор «PASS».
Обсудить в форуме
Once you send the request, API sends the response. A response is a message the server receives in return for a Request we send. When we send the request, then server accepts that request in and sends back a packet of the requested information, which is called the response. Each response depends on the sent request.
The server responds differently for every request, and it will be good if we take out some info from all of the server responses. It provides a user-friendly interface to see multiple pieces of information from all of the responses easily.
The postman response interface has multiple options. Let’s see these options one by one:
Response Status and Information
Enter the URL www.javatpoint.com and see the response:
On the top right corner of the response box, we can see the Status, Time, and Size of the code.
Status Code
A status code defines the status of the request. On entering URL, a mistake can be typed in the URL, or there may be a server-side problem. Status code is used to know about what went wrong and where you made a mistake. There are different status codes, and each of the status codes has different meanings.
Let’s see some standard status codes:
200: This code is used for a successful request.
201: For a successful request and data was created.
204: For empty response.
400: This is used for Bad Request. If you enter something wrong or you missed some required parameters, then the request would not be understood by the server, and you will get 400 status code.
401: This is used for Unauthorized Access. If the request authentication failed or the user does not have permissions for the requested operations, then you will get a 401 status code.
403: This is for Forbidden or Access Denied.
404: This will come if the Data Not Found.
405: This will come if the method not allowed or if the requested method is not supported.
500: This code is used for Internal Server Error.
503: And this code is used for Service Unavailable.
Time
Time is the duration between the sent request time and the received response time. Means, this is the duration which the response took after we sent the request and received the response.
This is very useful sometimes because many projects have a Service Level Agreement (SLA). The time shown here is not the actual time that the request will take. It is just approximate time, but you can consider this as an actual time.
Size
Size is the size of the response when it is processed within memory. This response size includes the size of response, cookies, headers, and everything that has been transmitted along with the response.
Response Body
A Response body is the body of the response, which actually contains the response content that has been sent from the server. In this section, you can see the web page code is sent to us as a response.
In this box, there are three ways to see the response in the response body:
- Pretty
- Raw
- Preview
Pretty: As the name specifies, pretty is the prettier way to see the content. In this option, code will colorfully show with different keywords and have indentations in the code, which is useful for reading. Each color has different meanings. This makes the code nicer.
Raw: This is almost similar to pretty but shows the code without colors and in single lines. It is just a raw version of the code without any colorful keywords.
Preview: This will show the preview of the page that has been sent. It has the same page been run inside a browser. You just need to click on the preview, and you will get the exact page as you would have seen inside a browser.
Preview tab renders the response in a sandboxed iframe, and because of iframe sandbox restrictions, JavaScript and images are disabled in the iframe.
Format Type
Each request has a defined response to it as defined by the Content-Type header. That response can be in any format. Such as in the below example we have HTML code file:
You will see that we have multiple format types:
- JSON
- XML
- HTML
- Text
- Auto
Sometimes, the server sends the response in multiple formats. The type of format of response will be visible to its corresponding format type.
Copy Response
From the right-hand side of the response box, you can see two rectangles; that option is used for copying the complete response to the clipboard, which is very useful to send the response to anyone.
Cookies
Cookies are the small size of files which contain the information related to server files or website pages. Once you open the website for the first time, a cookie file will download on your system. This cookie has some information which will be used by the same site when you visit again. This allows the website to give a specific response and specific information according to your last visit.
Postman offers you to see the cookies that have been sent from the server as a response. We cannot make any changes to the cookies since we got from the server.
Try with the URL www.google.com and go to the Cookies section, you will get the cookie.
Headers
Headers are the extra information that is transferred to the server or the client. In the postman, headers will show like key-value pairs under the headers tab.
Once you select Headers option, you will get the following info:
In the last tutorial we learnt about Get Request in Postman. In this tutorial we will understand how to deal with Response in Postman. It will be beneficial if you understand the underlying details of an HTTP Request and an HTTP Response.
What is Response?
A Response is a message that is received by the server in return to a Request that we send. When we request something, the server acts upon the Request and sends back a packet of the requested information. A response depends on the request mainly. Every request has a different kind of response and it is very important that we extract useful information from all of the responses. Postman has a beautiful interface for response and is very user-friendly. We can see a lot of information in the Postman for any response without doing much effort, or any if I might say.
You may also go through the recording of the Postman Tutorial where our experts have explained the concepts in depth.
Understanding Response in Postman
Talking about Response in Postman, the Response user interface contains lots of different things. We will deal with them in detail in this tutorial. The user interface has the following information blocks
- Response Status and Information
- Response Body
- Response Cookies
- Response Header
Let’s start by getting a response for www.google.com which looks like this:
Response Status and Information
Status Code :
A status code tells you the status of the request. There can be a lot of mistakes in the request and without looking at the status code, we might not always get what went wrong to our request. Sometimes, there can be a typing mistake in the URL or there can be a problem at the server-side, status code help us know about what went wrong (if something went wrong). There are different status codes and each of them has a different meaning.
You can learn about the complete list of status code here.
Status code 200 OK means that the request was correct and the desired response has been sent to the client. Now, change the URL to http://restapi.demoqa.com/utilities/weatherfull/city/hyderabd . Press Send and see the status code now.
It says 400 BAD REQUEST. It is so because we have changed the name of the city from Hyderabad to Hyderabad. This means the request was not correct, hence the bad request response. Similarly, you can see other status codes also for different requests.
Time
Time is the duration which the response took after we sent the request and received the response. This is very important sometimes because many projects have Service Level Agreements(SLA) for the time it should take a web service to return a response, this time can be a used to determine the SLA of the web service endpoint.
NOTE: The time given here is not the actual time that the request will take. It is just approximate but almost what it would be because there are a lot of things that Postman do after getting a response such as formatting and dividing Headers and cookies separately. As the additional work by Postman can be roughly considered as a constant time (WebServiceTime + Constant processing time by Postman). Therefore, it is an approximate of the time and is proportional to what the actual time will be. So you can consider this as actual time as well.
Size
Size is just the response size when it will be saved inside the memory. This response size is the size of complete response and headers and cookies and everything that has been sent along with the response.
NOTE: The response size that is shown in the Postman is approximate response size and not the exact size.
Response Body
A body depicts the body of the response, which is the main response content, that has been sent from the server. In this case as you can see it is a web page code being sent to us as a response. Now, there lie three ways ahead of us to look at this response:
Pretty
Pretty is a prettier version of the content being sent. The content is prettier as it is more readable. It has coloured keywords and different colours have different meanings. This makes a code more readable and look nicer. This formatting is done by Postman itself after getting the code.
Raw
Once you click on Preview you will get just the plain view of the content, as received from the server. It is just a raw version of the code without any colorful keywords. By looking at this code you might get why the other code is called «Pretty«.
Preview
Preview of the code will show you the preview of the page, had the page been run inside a browser. Click on preview and you will see the exact page as you would have seen inside a browser. So this would let you know the response preview without visiting the browser.
Format Type
As discussed above, a request has a defined response to it as defined by the Content-Type header. That response can be in any format. For example, in this case we have the response as a HTML code file.
Postman is smart enough to detect the response type and show you in the desired format, but sometimes Postman can also make a mistake. For example, use http://restapi.demoqa.com/utilities/weatherfull/city/hyderabad to get a response.
You will see that we have received a status code 200 and still there is no response. This is because Postman has failed to recognize the format of the response and is expecting a HTML file as seen in the dropdown.
Select Text in dropdown and you will be able to see the response now.
Sometimes, the server sends the response in two or more different formats. The type of response will be visible to its corresponding format type.
Note: Content-Type header defines the format of the response. For e.g. the Content-Type header may say that the response is JSON, however, the content being sent is XML or a malformed JSON. In that case Postman will not be able to do much. Take it as an exercise to understand why Postman is not able to understand the format of response returned by http://restapi.demoqa.com/utilities/weatherfull/city/hyderabad
Copy Response
The icon with two rectangles that you see in the corner is used for copying the complete response to the clipboard which is very handy to send the response to your teammates or using afterwards.
Cookie
Cookies are the small files which are related to the server files (website pages). Once you visit a website for the first time, a cookie is downloaded on the client’s machine. This cookie contains the information which can be used by the same website when you visit again. This helps the website to get you the specific response and specific information based on your last visit. In postman we can clearly see the cookies that have been sent from the server as a response. This makes it easy for the client to see what cookies are being saved inside his browser. We cannot manipulate this cookies since they are sent from server, Postman is used just to separate it from the response and have a clear view.
Header
Headers in an HTTP request or response is the additional information that is transferred to the user or the server. In postman, the headers can be seen in the Headers tab.
Once you click on header you can see different information such as below. Although, every entry in the Headers tab is a header item we will just take a look at the most important ones.
- Content-Type : This is the content type of the response. In the above example when we used www.google.com the content type is given as text/HTML because the response is being sent in the HTML which is one of the options.
- Date : This option shows the date, day and time of the response along with the time zone.
- Server : This option tells the name of the server which has responded to the request. In the above example, the server name is shown as gws which corresponds to Google Web Server.
- Cookie expire time : As the name suggests, this option tells the expire time of the cookie that has been sent along with the response.
There might be cases when your API doesn’t work, or exhibits unexpected behavior. If you’re not getting any response, Postman will display a message about an error in connecting to the server.
For more details about the possible causes of the error, open Postman Console. It has detailed information about the failure.
Consider these issues as you troubleshoot API requests.
Connectivity issues
If Postman is unable to connect to your server, it shows the message above. Usually, the easiest way to check if there are connectivity issues is to open your server address in a browser, such as Chrome or Firefox. If opening it in the browser works, then the possible causes could be:
Firewall issues
Some firewalls may be configured to block non-browser connections. In this case, you should talk to your network administrators for Postman to work.
Proxy Configuration
If you are using a proxy server to make requests, make sure you configure it correctly. By default, Postman uses the proxy settings configured in your Operating System’s network settings. Postman Console will provide debug information about the proxy server.
SSL Certificate issues
When using HTTPS connections, Postman might show the error above. In this case, you can turn off SSL verification in the Postman Settings. If that does not help, your server might be using a client-side SSL connection, which you can configure in Postman Settings. Use the Postman Console to ensure that the correct SSL certificate is being sent to the server.
Client Certificate issues
Client certificates might be required for this server. Fix this by adding a client certificate in the Postman Settings.
Incorrect Request URLs
If you use variables in your request, make sure they are defined in your environment or globals. Unresolved request variables may result in invalid server addresses.
Using incorrect protocol
Check whether you’re accidentally using “https://” instead of “http://” in your URL (or vice versa).
Invalid Postman behavior
Very rarely, it is possible that Postman might be making invalid requests to your API server. You can confirm this by checking your server logs (if available). We’re always watching out for these cases, so get in touch with us if you believe Postman is misbehaving. Let us know on our GitHub issue tracker if you feel that Postman is not working as intended.
Very short timeouts
If you configure a very short timeout in Postman, the request might timeout before completion, resulting in the error block above. Try increasing the timeout to avoid this issue.
Invalid Responses
If your server sends incorrect response encoding errors, or invalid headers, Postman will fail to interpret the response, causing the error above.
If you still can’t get your API working, help can frequently be found in the Postman community or Stack Overflow.
If you’ve tried unsuccessfully troubleshooting the issue, search the Postman issue tracker on GitHub to check if someone has already reported the issue and whether there is a known solution that you can use. If you’re reporting a new issue, follow these guidelines. If you wish to include confidential data, you can file a ticket via our support center and include the app’s console logs in your report to provide some helpful data for troubleshooting.

In the previous articles on Postman Tutorial, we have covered “How To Generate Advanced HTML Reports, While Using Newman“
In this “How To Fix Common Errors In Postman” article, I will be demonstrating how you can implement this concept and get a tight grip over this.
Common Error in Postman #1:
If we have an environment variable as {{url}. We cannot write inside script as pm.sendRequest({{url}}/item/). The syntax {{url}} works only inside the request builder and not in scripts.
Example:
var requestUrl = pm.environment.get(("url") + "/item/"); pm.sendRequest(requestUrl, function(err, res){ //Write test here });
Common Error in Postman #2:
If we want to trigger another request from a pre-request script, we can do it by using postman.setNextRequest
Example:
Postman.setNextRequest('request name as saved in Postman');
Common Error in Postman #3:
If we want to compare already saved variables (eg. Username) with values from another API response, we can use a method.
Example:
pm.test ("Your test name", function(){ var jsonData = pm.response.json(); pm.expect(jsonData.value).to.eql(pm.globals.get("username")); });
Common Error in Postman #4:
If we have a script like this:
pm.test("Test Name", function () { var jsonData = pm.response.json(); pm.expect(jsonData.name).to.eql('John'); }); pm.globals.set('name', jsonData.name);
Sometimes we get the error “ReferenceError: jsonData is not defined” while setting the global variable. To fix this, we need to define jsonData outside the function.
var jsonData = pm.response.json(); pm.test("Name should be John", function () { pm.expect(jsonData.name).to.eql('John'); }); pm.globals.set('name', jsonData.name);
Or we can set the environment or global variable inside the function.
pm.test("Name should be John", function () { var jsonData = pm.response.json(); pm.expect(jsonData.name).to.eql('John'); pm.globals.set('name', jsonData.name); });
Common Error in Postman #5:
If we want to set a delay while running a collection in Newman, we can use — delay parameter and specify delay in milliseconds.
newman run collection.json -- delay 10000
Common Error in Postman #6:
If Jenkins shows weird characters in the console, it means output is in Unicode format. To fix this, either use View as Plain text option or add following flags: — disable-unicode
Example:
newman run collection.json – disable-unicode
Next steps:
Learn “GUID in Postman” in the next tutorial.
Related posts:
- Postman Tutorial
- API Testing Tutorial
- API Testing Interview Questions