Postman is one of the most popular software testing tools which is used for API(Application Programming Interface). With the help of this tool, developers can easily create, test, share, and document APIs.

Introduction to Postman

Postman is a standalone software testing API (Application Programming Interface) platform to build, test, design, modify, and document APIs. It is a simple Graphic User Interface for sending and viewing HTTP requests and responses

  • While using Postman, for testing purposes, one doesn't need to write any HTTP client network code. Instead, we build test suites called collections and let Postman interact with the API.

In this tool, nearly any functionality that any developer may need is embedded. This tool has the ability to make various types of HTTP requests like GET, POST, PUT, PATCH, and convert the API to code for languages like JavaScript and Python.

The primary or most-commonly-used HTTP verbs (or methods, as they are properly called) are POST, GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD) operations, respectively. There are a number of other verbs, too, but are utilized less frequently. Of those less-frequent methods, OPTIONS and HEAD are used more often than others.

Below is a table summarizing recommended return values of the primary HTTP methods in combination with the resource URIs:

HTTP VerbCRUDEntire Collection (e.g. /customers)Specific Item (e.g. /customers/{id})
POST --->Create201 (Created), 'Location' header with link to /customers/{id} containing new ID.404 (Not Found), 409 (Conflict) if resource already exists..
GET --->Read200 (OK), list of customers. Use pagination, sorting and filtering to navigate big lists.200 (OK), single customer. 404 (Not Found), if ID not found or invalid.
PUT--->Update/Replace405 (Method Not Allowed), unless you want to update/replace every resource in the entire collection.200 (OK) or 204 (No Content). 404 (Not Found), if ID not found or invalid.
PATCH --->Update/Modify405 (Method Not Allowed), unless you want to modify the collection itself.200 (OK) or 204 (No Content). 404 (Not Found), if ID not found or invalid.
DELETEDelete405 (Method Not Allowed), unless you want to delete the whole collection—not often desirable.200 (OK). 404 (Not Found), if ID not found or invalid.

Below is a more-detailed discussion of the main HTTP methods. Click on a tab for more information about the desired HTTP method.

  • POST

    The POST verb is most-often utilized to create new resources. In particular, it's used to create subordinate resources. That is, subordinate to some other (e.g. parent) resource. In other words, when creating a new resource, POST to the parent and the service takes care of associating the new resource with the parent, assigning an ID (new resource URI), etc.

    On successful creation, return HTTP status 201, returning a Location header with a link to the newly-created resource with the 201 HTTP status.

    POST is neither safe nor idempotent. It is therefore recommended for non-idempotent resource requests. Making two identical POST requests will most-likely result in two resources containing the same information.

    Examples:

    • POST example.com/customers

    • POST example.com/customers/12345/orders

      GET

    • The HTTP GET method is used to read (or retrieve) a representation of a resource. In the “happy” (or non-error) path, GET returns a representation in XML or JSON and an HTTP response code of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD REQUEST).

      According to the design of the HTTP specification, GET (along with HEAD) requests are used only to read data and not change it. Therefore, when used this way, they are considered safe. That is, they can be called without risk of data modification or corruption—calling it once has the same effect as calling it 10 times, or none at all. Additionally, GET (and HEAD) is idempotent, which means that making multiple identical requests ends up having the same result as a single request.

      Do not expose unsafe operations via GET—it should never modify any resources on the server.

      Examples:

      • GET example.com/customers/12345

      • GET example.com/customers/12345/orders

      • GET example.com/buckets/sample

        PUT

        PUT is most-often utilized for update capabilities, PUT-ing to a known resource URI with the request body containing the newly-updated representation of the original resource.

        However, PUT can also be used to create a resource in the case where the resource ID is chosen by the client instead of by the server. In other words, if the PUT is to a URI that contains the value of a non-existent resource ID. Again, the request body contains a resource representation. Many feel this is convoluted and confusing. Consequently, this method of creation should be used sparingly, if at all.

        Alternatively, use POST to create new resources and provide the client-defined ID in the body representation—presumably to a URI that doesn't include the ID of the resource (see POST below).

        On successful update, return 200 (or 204 if not returning any content in the body) from a PUT. If using PUT for create, return HTTP status 201 on successful creation. A body in the response is optional—providing one consumes more bandwidth. It is not necessary to return a link via a Location header in the creation case since the client already set the resource ID.

        PUT is not a safe operation, in that it modifies (or creates) state on the server, but it is idempotent.

      • (What do you mean by idempotent?

        Idempotence is any function that can be executed several times without changing the final result beyond its first iteration.).
        In other words, if you create or update a resource using PUT and then make that same call again, the resource is still there and still has the same state as it did with the first call.

        If, for instance, calling PUT on a resource increments a counter within the resource, the call is no longer idempotent. Sometimes that happens and it may be enough to document that the call is not idempotent. However, it's recommended to keep PUT requests idempotent. It is strongly recommended to use POST for non-idempotent requests.

        Examples:

        • PUT example.com/customers/12345

        • PUT example.com/customers/12345/orders/98765

        • PUT example.com/buckets/secret_stuff

          PATCH

          PATCH is used for modify capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource.

          This resembles PUT, but the body contains a set of instructions describing how a resource currently residing on the server should be modified to produce a new version. This means that the PATCH body should not just be a modified part of the resource, but in some kind of patch language like JSON Patch or XML Patch.

          PATCH is neither safe nor idempotent. However, a PATCH request can be issued in such a way as to be idempotent, which also helps prevent bad outcomes from collisions between two PATCH requests on the same resource in a similar time frame. Collisions from multiple PATCH requests may be more dangerous than PUT collisions because some patch formats need to operate from a known base-point or else they will corrupt the resource. Clients using this kind of patch application should use a conditional request such that the request will fail if the resource has been updated since the client last accessed the resource. For example, the client can use a strong ETag in an If-Match header on the PATCH request.

          Examples:

          • PATCH example.com/customers/12345

          • PATCH example.com/customers/12345/orders/98765

          • PATCH example.com/buckets/secret_stuff

            DELETE

            DELETE is pretty easy to understand. It is used to delete a resource identified by a URI.

            On successful deletion, return HTTP status 200 (OK) along with a response body, perhaps the representation of the deleted item (often demands too much bandwidth), or a wrapped response (see Return Values below). Either that or return HTTP status 204 (NO CONTENT) with no response body. In other words, a 204 status with no body, or the JSEND-style response and HTTP status 200 are the recommended responses.

            HTTP-spec-wise, DELETE operations are idempotent. If you DELETE a resource, it's removed. Repeatedly calling DELETE on that resource ends up the same: the resource is gone. If calling DELETE say, decrements a counter (within the resource), the DELETE call is no longer idempotent. As mentioned previously, usage statistics and measurements may be updated while still considering the service idempotent as long as no resource data is changed. Using POST for non-idempotent resource requests is recommended.

            There is a caveat about DELETE idempotence, however. Calling DELETE on a resource a second time will often return a 404 (NOT FOUND) since it was already removed and therefore is no longer findable. This, by some opinions, makes DELETE operations no longer idempotent, however, the end-state of the resource is the same. Returning a 404 is acceptable and communicates accurately the status of the call.

            Examples:

            • DELETE example.com/customers/12345

            • DELETE example.com/customers/12345/orders

            • DELETE example.com/bucket/sample

            • API->Application Programming Interface (API) is software that acts as an intermediary for two apps to communicate with each other. We use APIs whenever we use an application like Twitter, Facebook, sending text messages, or checking the weather over the phone.

              HTTP

              HTTP (Hypertext Transfer Protocol) is the collection of rules for the transmission of data on the World Wide Web, like graphic images, text, video, sound, and other multimedia data. The Web users implicitly make use of HTTP as soon as they open their Web browser.

              Example: A user or browser enters the HTTP request to the server; the server then returns the user response. This response includes the request status information and may consist of the requested material as well.

              The most commonly used HTTP methods are GET, POST, PUT, PATCH, HEAD, DELETE, and OPTIONS.

              Why use Postman?

              Postman is based on a wide range of extremely user-friendly power tools. For more than 8 million users, Postman has become a tool of convenience. Following are the reasons why Postman is used:

            • Accessibility- One can use it anywhere after installing Postman into the device by simply logging in to the account.

            • Use Collections-Postman allows users to build collections for their API-calls. Every set can create multiple requests and subfolders. It will help to organize the test suites.

            • Test development- To test checkpoints, verification of successful HTTP response status shall be added to every API- calls.

            • Automation Testing-Tests can be performed in several repetitions or iterations by using the Collection Runner or Newman, which saves time for repeated tests.

            • Creating Environments- The design of multiple environments results in less replication of tests as one can use the same collection but for a different setting.

            • Debugging- To effectively debug the tests, the postman console helps to track what data is being retrieved.

            • Collaboration- You can import or export collections and environments to enhance the sharing of files. You may also use a direct connection to share the collections.

            • Continuous integration-It can support continuous integration.

Prerequisites

  • Before proceeding with this tutorial, you should have a basic knowledge of API, automation, and manual testing.

    Postman Installation and Updates

    Postman can be downloaded for all major operating systems, including Mac, Linux, and Windows, as a native app (standalone application). Postman is also available as a chrome extension application, but it is better to install and use the native app because Postman chrome extension does not support all the features that the native app has.

    Introduction to Postman

    For developers, Postman is the API Platform to build, test, iterate, and design their APIs. Postman reports that it has 25+ million registered users and 75k open APIs as of February 2023, which it tells constitutes the largest public API hub in the world. The organization is in San Francisco and has an office in Bangalore, in which it was discovered.

  • History of Postman

    In 2012, Postman started as Abhinav Asthana's side project, who wanted to clarify API testing, during work at Yahoo Bangalore. As a free app, Abhinav Asthana launched Postman in Chrome Web Store. He recruited old colleagues Abhijit Kane and Ankit Sobti to help in creating Postman Inc. as the usage of the app grew. Today, these three co-founders run the company, where Sobti serves as CTO and Abhinav as CEO.

    Products of Postman

    API repository: It permits the user to save, catalog, and cooperate across API artifacts within a central platform in partner, private, or public networks.

    • One truth source for APIs: Postman offers a centralized, version-controlled, and cloud-based repository for every API artifact from the whole API lifecycle. Every tool of the Postman platform uses the repository, which guarantees one truth source for our APIs. This API repository allows organizations and teams to assemble metrics and detect insights from the built-in governance facilities in the platform.
      The web and desktop applications of Postman link to the API repository by workspaces for public, partner, team, and personal use. Also, we can connect our API repository to other tools and products we use by the pre-built integrations of Postman. We can better scale, organize, and simplify our whole API lifecycle with the API repository of Postman, whether it is for one API or for our whole API landscape.

      • Tools: API detection, mock servers, API testing, API documentation, API design, and API client.

      • API builder: It helps in implementing the workflow of an API design with specifications, including RAML, GraphQL, and OpenAPI. It develops varied APM solutions, gateways, CI/CD, and source controls.

      • Intelligence: API governance, reporting, workspaces, API repository search, security warnings, etc.

      • Workspaces: Public, partner, team, and personal workspaces permit developers to cooperate externally and internally.

        Postman API development

        Postman Provides its support for API- initial development with API Builder. In Postman, we can apply the API Builder to develop our API. Then, our API definition can act as one truth source for our API project. We can connect many elements of our API development and inspection process to our API definition, including monitors, tests, documentation, and collections. Also, we can sync our API with the Git repository in Postman.

High-level steps

Below are some high-level steps required when designing and integrating APIs:

  • Creating API: We can begin a new API in the first step in Postman.

  • With API version control: We can sync our modifications between the remote Git repository and Postman. We can also release a version when we are ready to distribute our modifications to customers.

  • Developing API: We can build our API by adding collections and editing our API definition. Also, we can produce server-side code from our OpenAPI 3 specification and validate our API definition and attached elements.

  • Testing API: We can add tests to our API and apply CI integration to create and automate the testing process.

  • Deploying API: We can connect our API deployment service to include greater visibility in Postman.

  • Monitoring API: We can add monitors to inspect our API.

  • Handling and sharing APIs: We can share our APIs with several team members, see changes, view changelog, and add comments.

  • Mocking API: We can configure a mock server to reproduce the endpoints of our API to test and development purposes.

  • API reports: We can use reports to see statistics, including the improvement, development, and usage done by our team on APIs.

Navigate API Builder

To see and implement APIs, we can choose APIs inside the sidebar. We can open and change any previous APIs or create or ship new APIs. We can utilize the arrows to increase API within the sidebar and see the linked elements and definition files of API.

When we choose API, the workbench shows the API overview. This overview shows the API description, published versions, and linked collections. Also, the overview offers quick access to operations, including viewing deployments, inspecting the API, adding tests, and connecting to any repository.

Steps to download and install the native Postman application

Step-1: Go to the link https://www.postman.com/downloads/ and click download for Mac or Windows or Linux based on your operating system.

Installation and Updates

Step-2: For downloading the app for Windows, click on the download button and select the particular version. I opted for the 64-bit version. If you are using a 32-bit OS, you can choose the 32 bit, as shown in the above image.

Step-3: You can check the download progress on the bottom left if you are using the Chrome browser. Once the .exe file is downloaded, you need to install the application, as shown in the below image.

Installation and Updates

Step-4: Once the installation completes, you will be redirected to a window as shown in the image where you can click on Stop signing in and take me straight to the app (as this app can also be used without logging in) or otherwise you will get a new window to sign up.

Installation and Updates

It is better to create an account as this will help you to save the work you do within the Postman, and with this, you won't lose any work.

Step-5: Create your account with all the required details, or you can also signup with Google, as shown in the image.

Installation and Updates

Step-6: After signing in, select the workspace tools as per your requirement, and then click on, continue to get the startup screen.

Installation and Updates

Step-7: You will see the following page, and then you are ready to use Postman.

Installation and Updates

Steps to update the Postman

  • You will receive a notification in your Postman app if any update is available.

  • To download or install the latest update, click on the Settings icon, as shown in the image below, go to Settings>Update.

    Installation and Updates

  • You can change the update settings by enabling the settings of automatically download major updates, as shown in the image below.

    Installation and Updates

  • You can also check for the latest updates by clicking on Check for updates, which will show you if any new update is available.

  • You will have to select the update option to download and install the latest update. When the download is complete, you will see a notification asking you to restart the app to install the updated features.

  • It automatically downloads minor updates and bug fixes.

    [Note-->PARAMS=A parameter is a part of the URL used to pass more information to the server. The data can be used in the form of a data file or an Environment variable. Parameterization is an important feature of Postman and helps to eliminate redundant tests. Parameters are enclosed in double curly braces {{parameter}}.]

  • The HEAD method is used to ask only for information about a document, not for the document itself. HEAD is much faster than GET, as a much smaller amount of data is transferred. It's often used by clients who use caching, to see if the document has changed since it was last accessed.

  • What is head in API?

    What is the HEAD Method? The HEAD method is used to retrieve the header information of a resource. This method is similar to the GET method, but it does not return the body of the response. Instead, it only returns the header information, such as the content type, content length, and other metadata.

What is the OPTIONS Method?

  • The OPTIONS method is used to retrieve the communication options for a resource. This method is used to determine what methods are allowed for a particular resource. For example, if a resource supports the GET, POST, and PUT methods, the OPTIONS method will return this information.

    Postman Navigation

    After downloading and installing Postman in our system, we will now discuss the user interface of Postman to learn about the features and terminologies that Postman offers.

    We can split the postman navigation into four UI structures, as shown in the image below.

    Postman Navigation

  1. Header bar

  2. Sidebar

  3. Builder section

  4. Response section

1. Header bar

Header bar contains the following options-

New

Postman Navigation

The new option is used for the following tasks

Request

It is used to create a new request, where you can create and save requests by entering the request name and can use it in the future.

Postman Navigation

Collection

It saves your requests in the form of a collection for reusing and sharing.

Postman Navigation

Environment

Environments are variables with key-values. Every variable name represents its key. So if we reference the name of the variable, it enables us to access its corresponding value. So it basically saves the values you frequently use in an environment.

Postman Navigation

The new button also provides some advanced features like--

Documentation - to create documentation for API,

Mock server- to create in-development APIs,

Monitor- to test API performance,

API - for managing all aspects of APIs, including design, development, and testing.

  • Import

You may use the Import option for importing files in different formats into the software. As seen in the image below, you can import Postman collection and Environment files from any location and can run it through postman.

Postman Navigation

  • Runner

This option helps to directly run the loaded collections in the Postman.

Postman Navigation

  • Open new icon

This option is used to open a new Tab, a new Postman window, and a new Runner window.

Postman Navigation

  • My Workspace

This option helps you to view, manage, and create personal as well as team workspaces. Collections, monitors, environments, and mocks are components of the workspace.

Postman Navigation

  • Invite

This is used to invite other users into your team to collaborate with them for team workspace. As seen in the image below, this can be done by entering the email address or uploading the list of people to invite them.

Request

It is used to create a new request, where you can create and save requests by entering the request name and can use it in the future.

Postman Navigation

Collection

It saves your requests in the form of a collection for reusing and sharing.

Postman Navigation

Environment

Environments are variables with key-values. Every variable name represents its key. So if we reference the name of the variable, it enables us to access its corresponding value. So it basically saves the values you frequently use in an environment.

Postman Navigation

The new button also provides some advanced features like

Documentation - to create documentation for API,

Mock server- to create in-development APIs,

Monitor- to test API performance,

API - for managing all aspects of APIs, including design, development, and testing.

  • Import

You may use the Import option for importing files in different formats into the software. As seen in the image below, you can import Postman collection and Environment files from any location and can run it through postman.

Postman Navigation

  • Runner

This option helps to directly run the loaded collections in the Postman.

Postman Navigation

  • Open new icon

This option is used to open a new Tab, a new Postman window, and a new Runner window.

Postman Navigation

  • My Workspace

This option helps you to view, manage, and create personal as well as team workspaces. Collections, monitors, environments, and mocks are components of the workspace.

Postman Navigation

  • Invite

This is used to invite other users into your team to collaborate with them for team workspace. As seen in the image below, this can be done by entering the email address or uploading the list of people to invite them.

  • Sync icon

This option is used to synchronize the API requests that you send from other devices and updates your postman account status.

Postman Navigation

  • Interceptor icon

The interceptor option is a proxy server, used to capture all the requests that you send through browser or phone or from any other device.

  • Settings icon

Postman Navigation

  • Notification icon

It shows all the notification of the Postman app.

2. Sidebar

Postman Navigation

  • History
    The history option is situated below the filter section of the app. The History tab automatically keeps a record of all your API requests, just like any other browser. It keeps handy all your past searches.

  • Collections
    The collection is the group of related requests which are displayed under the collection tab. In the collection tab, you can also create a new collection, as shown in the picture below. There is also a
    Trash section from where you can recover your lost or deleted collections.

Postman Navigation

  • APIs

All the APIs are listed in this section. New API can also be created from this tab.

Postman Navigation

3. Builder or Request section

Postman Navigation

  • Untitled Request

'Untitled request' is basically the default request title you are working on. The title depends on the type of request method you are working on, as shown in the image below.

Postman Navigation

  • HTTP request

Postman Navigation

This option opens a drop-down list of all the HTTP request methods, as shown in the image like GET, DELETE, PATCH, OPTIONS, LINK, POST, COPY, UNLOCK, PURGE, etc. In general, we mostly use POST and GET. We will discuss these requests in later chapters.

  • Request URL or Endpoint

This URL option is like any other browser URL. In this, we mention the link to where the API will communicate with.

Postman Navigation

  • Params

This option is used to write the parameters of the request. These parameters include key values and descriptions.

Postman Navigation

  • Authorization

The authorization process is required to access the APIs. This process verifies whether you have permission from the server to access the data you want. We will discuss this as a complete chapter later on.

Postman Navigation

  • Headers

An HTTP request header is the additional data that is required to send along with the request. This header information is required for proper two-direction communication between the client and the server.

  • Body

It let you specify the data type that you need to send with a request. There are various types of body data that you can send to match your API.

Postman Navigation

  • What is an SSL certificate?

    An SSL certificate is a digital certificate that authenticates a website's identity and enables an encrypted connection. SSL stands for Secure Sockets Layer, a security protocol that creates an encrypted link between a web server and a web browser

  • Pre-request script

These are written in JavaScript, and as the name suggests, these are executed before sending the request. Generally, these scripts are for setting the environment and ensuring that the request is running in the right environment.

Postman Navigation

  • Test scripts

It is executed during the request. It is also written in JavaScript. This helps you to ensure that API works as intended. Testing is important as it sets up checkpoints to verify whether the response status is ok and retrieved data is as expected.

Postman Navigation

4. Response section

The API responses which are sent back from the server are shown in the response window. These are generated after you send an API request to the server. As we have not sent any request, so there is no response in our case.

Postman Navigation

Postman Sending Your First Request

Sending a request is as easy as posting a URL into your web browser. We can easily send requests to APIs in Postman. An API request helps you to access, or send, data from a data source.

To send the API request, we need an HTTP method. Some commonly used methods are POST, GET, DELETE, PUT, and PATCH.

GET: This HTTP method is used to access the data from an API.

POST: This method transmits new data.

DELETE: This is used to remove or delete the existing data.

PATCH: This method is used to update the existing data.

PUT: This method is used to update the existing data.

Without any terminal or code, we can make API requests and review the answers with the help of postman. Just build a new request and select the send button, you'll get the API response.

Sending Your First Request

Sending a Request

Open the Postman app to send the first API request. Now, to open a new tab, click on the + plus button.

Sending Your First Request

You can also open the new tab by entering ctrl+T or from the Open New menu select Tab option.

Sending Your First Request

In the URL field, enter the following URL:

  1. postman-echo.com/get

Sending Your First Request

From the right side of the URL field, click on the Send button.

Sending Your First Request

In the lower pane, you will get the response in JSON data from the server.

  1. {

  2. "args": {},

  3. "headers": {

  4. "x-forwarded-proto": "https",

  5. "host": "postman-echo.com",

  6. "accept": "*/*",

  7. "accept-encoding": "gzip, deflate, br",

  8. "postman-token": "f4f37aba-a7e6-4fba-b4a7-a863b2bf627d",

  9. "user-agent": "PostmanRuntime/7.24.1",

  10. "x-forwarded-port": "80"

  11. },

  12. "url": "https://postman-echo.com/get"

  13. }

Sending Your First Request

Creating the First Collection

Collection in Postman means a group of API requests that you have already saved in the Postman. You can arrange these requests into folders.

Steps to Create the First Collection

  • Enter the new request in the Request URL option, which is present in the Builder section.

Creating the First Collection

  • Click on the Save button, and then a new window will open, as shown in the image below.

Creating the First Collection

  • You can change the Request name, or by default, Request URL will be displayed as the Request name.

  • You can also write the Request description as an optional step.

  • Now go to create a collection option and write a name to your collection. I have named it First Collection, as you can see in the image above.

  • Save your collection by clicking on the Save button.

  • Now, after saving, you can see your collection in the sidebar under the Collection tab, as shown in the image below.

  • Within a collection, any number of requests can be added.

Creating the First Collection

SENDING API REQUEST

Creating Requests

Let's create a new request in Postman. In the request, we can have many details. And during this request creation process, you have to enter a URL and select the method. Other than you can optionally specify the number of additional information.

To create a request, follow the following steps:

Step 1: Launch the Postman.

Step 2: Click on New option from the top left corner of the Postman homepage window. Once you click on the button, a drop-down menu will open.

Creating Requests

Step 3: Click on the Request option from the drop-down list.

Creating Requests

Step 4: Once you select the Request option, you will be prompted to enter the request name, and you can also describe that API for future use. The description section is optional; we can leave it blank.

Here my Request name is "My API."

Creating Requests

Step 5: Scroll down and click on + Create Collection.

Creating Requests

Enter the collection Name (here, 'Collection-01' is my collection name) and click on the right mark.

Creating Requests

Step 6: Click on the Save button to create your request.

Creating Requests

Once you click on the save button, a new tab will open with your given request name.

Creating Requests

Step 7: Enter javatpoint.com in the address bar and click on Send.

Creating Requests

Once you select the Send, you will get the following response.

Creating Requests

Setting Request URLs

For sending the request, you should have a URL that defines the API endpoint. All API operation is usually associated with an endpoint, which is a place from where these APIs can access the resources that are required to perform their task.

To access the API in Postman, you need to enter the URL, and each URL contains an endpoint.

  • When you create an API, usually, the URL is the base location plus path. For example, javatpoint.com/java-tutorial, where javatpoint.com is the base URL and /java-tutorial, is the endpoint path.

    Creating Requests

  • And if you use a third-party API, then you don't need to supply the URL, your API provider will supply the URL you need.

Selecting Request Methods

Once you enter the URL in the URL text field, the GET method will be selected for new requests by default. There are multiple other methods available.

Creating Requests

Some commonly used methods are:

GET: This HTTP method is used to retrieve data from an API.

POST: To send the new data to an API, we can use this method.

DELETE: This is used to remove or delete the existing data.

PATCH: This method is used to update the existing data.

PUT: This method is used to update the existing data

Authorizing Requests

  • Authorizing requests include authenticating the identity of the client who sends the request and verifies whether the client is allowed to access and conduct the endpoint operations. APIs use authorization details to make sure that the client requests access data safely.

  • Several authorization types are available in Postman that you can use while creating an API.

  • You need to ask the provider for any authorization details you require while using third party API.

Steps for Authorizing Requests in Postman

  • Open the Postman app and enter a request in the Request URL section.

  • Under the Authorization, the tab selects the authorization TYPE from the drop-down menu, as shown in the image below.

Authorizing Requests

The various authorization types are--

  • Inherit auth from parent
    This is the default auth type. In this, authorization type will be the same as the parent, which means whatever the auth type you selected for that collection (parent); the same auth type will be selected for the request, which is under that collection.

  • No Auth
    If you select this type, Postman will not send any auth data with the request
    .

  • API key
    This is to send the Key and Value along with the API request.

  • Bearer Token
    This auth type allows the Authorization of requests by using an access key.

  • Basic Auth
    This allows users to send username and password along with the request for API login.

  • Digest Auth
    This is the two-point authentication of your API request. In this auth type user will send a request where the server will reply with a number that can only be used once. Then the user again will send the request along with username, password, and that realm number for Authorization of the request.

  • OAuth
    This auth type is to access third-party API data
    .

  • Hawk Authentication
    This enables users to use partial cryptographic verification to authenticate their requests. Hawk Auth id, which is your API authentication ID value and Hawk Auth key, which is your API authentication key value, is required for Authorization under this auth type.

  • AWS Signature
    For Amazon Web Services requests, this auth type is used
    .

  • NTLM Authentication (Beta)
    This is the auth type for windows OS and standalone systems.

  • Akamai EdgeGrid
    Akamai technologies use this auth type for authorizing requests.

  • After choosing an Auth type, the app will indicate which part among header, body, URL, or params will include your data so that the user can see how these data will be sent before they run the request.

  • The authorization data can be sent as header, body, or as parameters to a request.

    Authorizing Requests

  • For example, the auth data is sent as headers, as shown in the image above, so these headers will be automatically sent along with the request.

  • GET Request in Postman

    Since now we know how to create the request in Postman, it's time to work on GET request. A GET request gets the information from the server. When you make the GET request on the server, then the server responds to the request.

GET request will not affect any data on the server. Means, there is no creation, updation, addition, or deletion of data on the server when you are making a GET request.

GET request contains all information inside the URL, and because of that, some people do not prefer to use GET request while they are sending some confidential data such as passwords. For example, if you search anything on Google, you actually using a GET request because there is no sensitive information, and you are just requesting the page. You can try to search for something on Google; you will get the same search string in the URL.

To create the first GET request in Postman, follow the following steps:

Step 1: Create a request. To create a new request, open a new tab, click from the + plus button.

GET Request in Postman

You can also open the new tab by entering ctrl+T or from the Open New menu select Tab option.

GET Request in Postman

Once you create a new request then you will get the following window:

GET Request in Postman

Step 2: Enter the URL in the address bar. We will use javatpoint.com.

GET Request in Postman

Step 3: Now, select the GET request from the list of request methods.

GET Request in Postman

Step 4: Now press send.

GET Request in Postman

Step 5: Once you press the send button, you will get the response from the server. Make sure you have a proper internet connection; otherwise, you will not get a response.

GET Request in Postman

You can check the status code. Here, we got the status code 200 200, which means we got a successful response for the request.

GET Request in Postman

In the Body tab of the response box, we have multiple options to see the response in a different format.

GET Request in Postman

Pretty: In this option, code will show colorfully with different keywords and have indentations in the code, which is useful for reading.

GET Request in Postman

Raw: This is almost similar to pretty but shows the code without colors and in single lines.

GET Request in Postman

Preview: This will show the preview of the page that has been sent.

Response in Postman

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 javatpoint.com and see the response:

Response in Postman

On the top right corner of the response box, we can see the Status, Time, and Size of the code.

Response in Postman

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

GET Request in Postman

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.

Response in Postman

In this box, there are three ways to see the response in the response body:

  • Pretty

  • Raw

  • Preview

Response in Postman

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.

Response in Postman

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.

Response in Postman

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.

Response in Postman

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:

Response in Postman

You will see that we have multiple format types:

  • JSON

  • XML

  • HTML

  • Text

  • Auto

Response in Postman

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.

Response in Postman

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 google.com and go to the Cookies section, you will get the cookie.

Response in Postman

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:

Response in Postman

Request Parameters in Postman

Request parameters are used to send additional information to the server. A URL contains these parameters. There are two types of parameters:

Query Parameter: These are appended to the end of the request URL, Query parameters are appended to the end of the request URL, following '?' and listed in key-value pairs, separated by '&' Syntax:

  1. ?id=1&type=new

Path Parameters: These are part of the request URL, which are accessed using the placeholders preceded by ':' Example:

  1. /customer/:id

There are two ways of setting query parameters on a request in Postman.

Using URL Field

The most common way of adding parameters is- append the query string to the end of the URL.

Let's enter a URL in the URL text field:

Suppose we have the URL google.com/search when you click on send option you will get the following response:

Request Parameters in Postman

Now try to enter the parameter in the following format:

.google.com/search?q=javatpoint

Here 'q' is the key, and 'javatpoint' is the value of the key.

When you enter the parameter in the URL and select the send button then you will get the following response:

Request Parameters in Postman

Using Params

Using Params is the second way. This option is available on the left side of the URL text field. This option will offer you additional text fields under the URL field to enter the query parameters in the form of key-value pairs.

Once you enter parameters in the Params text field, then these parameters will automatically be added to the URL. The interface offers to keep your entered parameters in an organized way, which is very useful for the requests that require several parameters.

Let's see an example:

Request Parameters in Postman

Enter the URL www.google.com/search in the URL text field:

And now go to the Params section:

Request Parameters in Postman

Write the parameters under the key-value pair, as shown. Here, k is the query, and javatpoint is the search term.

Request Parameters in Postman

Now press send button and look at the preview section of response window; you will get the following response:

Request Parameters in Postman

Multiple Parameters

We can also work with multiple parameters inside a single query. Just go to your browser and search in Google 'javatpoint'.

Request Parameters in Postman

https://www.google.com/search?q=javatpoint&rlz=1C1CHBF_enUS851US851&oq=javatpoint&aqs=chrome..69i57j0l5j69i60l2.3135j0j7&sourceid=chrome&ie=UTF-8

See the above image and URL; multiple parameters are sent in the URL.

In the above URL, '&' should be followed by a parameter such as &ie=UTF-8. In this parameter, i.e., is the key and, UTF-8 is the key-value.

Enter the same URL in the Postman text field; you will get the multiple parameters in the Params tab. Even you can write each of the parameters and send a request with multiple parameters.

Request Parameters in Postman

POST Request in Postman

The post is an HTTP method like GET. We use this method when additional information needs to be sent to the server inside the body of the request. In general, when we submit a POST request, we expect to have some change on the server, such as updating, removing or inserting.

One of the best examples of using POST request is the login page of Facebook or the login page of other sites; you send your personal information such as the password to the server. The server creates a new account with the same information and that account, and the information is added permanently on the Facebook server.

The POST request is a fundamental method, and this method is mostly used when a user wants to send some sensitive data to the server like to send a form or some confidential data.

Important points of the POST request:

  • POST requests will not take the cookies.

  • POST requests are not left in the history of browsers.

  • We cannot bookmark the POST requests.

  • There is no restriction of data length in POST requests.

In Postman, every endpoint of REST API is associated with its HTTP verb. When an endpoint states that it should be called using the POST http verb, then for calling the endpoint, only the POST HTTP Verb is required.

Let's first check with the GET request for a POST endpoint.

GET Request on POST Endpoint

Here, we have one API which is used to register a new customer:

http://restapi.demoqa.com/customer/register

Enter the URL in the postman endpoint bar, and press Send. Then select the GET method from the drop-down list.

POST Request in Postman

See the following response:

POST Request in Postman

See the HTTP status code, and you will get the "405 Method Not Allowed" error code. It means we are requested for an endpoint with the wrong method. And in the Pretty tab also you can see the fault error.

POST Request in Postman

This means we selected the incorrect method type. Now let's try to change the type of method and see if we will get the right response.

Post Request without Body

First, change the type of method from GET to POST and click on the Send button.

POST Request in Postman

Now, see the response section.

POST Request in Postman

Here, 400 Bad Request, as shown in the image above, indicates that the request and server parameters are not found matched to get a response. And from the response body, 'Invalid post data' means the entered post data is not valid.

So, we are required to add the information with the correct format within the request body.

Adding a Request body to the Post request- For this, select the Body tab.

POST Request in Postman

Now in the Body tab, select raw and select JSON as the format type from the drop-down menu, as shown in the image below. This is done because we need to send the request in the appropriate format that the server expects.

POST Request in Postman

In my example, server expects a json body that contains new user information. Here is one simple example:

  1. {

  2. "FirstName" : "value",

  3. "LastName" : "value",

  4. "UserName" : "value",

  5. "Password" : "value",

  6. "Email" : "value"

  7. }

Copy and paste the above example to your postman request Body. Just change the attribute value to the required value, like the below example:

POST Request in Postman

Finally, press Send and see the response body and response status.

POST Request in Postman

Here the status code is 200 OK; this means the server approved the request, and we received a positive response. The error "User already exists" means the data already exist in the database.

Let's enter the different value and check the response status:

POST Request in Postman

Press send and check the response:

POST Request in Postman

Here, "Operation completed successfully" means your entry has been created successfully, and your POST request has done successfully.

Sending Body Data

Since now, you know that we need to send the body data with requests whenever you need to add or update structured data.

Select the POST request method, and go to Body option where we have different options for sending data:

POST Request in Postman

Here you have:

  • none

  • form-data

  • x-www-form-urlencoded

  • raw

  • binary

  • GarphQL

form-data

form-data sends the form's data. Such as the information you enter while filling out a form.To send these details, write them as key-value pairs. Here, the key is the name of the entry, and value is the value of the entry you are sending. Follow the following steps:

  • Select form-data.

POST Request in Postman

  • Add the KEY-VALUE pair.

POST Request in Postman

x-www-form-urlencoded

It works similar to form-data. The only difference between both of them is that, when you sent the data via x-www-form-urlencoded, the url is encoded. Encoded indicates that the transmitted data is converted to various characters so that unauthorized persons cannot recognize the data.

POST Request in Postman

Raw

This is a very useful option while sending the body to the POST method. Here the body data will be presented in the form of a stream of bits.

In the above examples, we already discussed the raw. So, we will not discuss it again.

Binary

Binary is used to send the data in a different format. Such as a file, image, etc. To use this option, select binary and then click on Select File to browse any file from your system.

POST Request in Postman

GraphQL

Through this option, you can send the GraphQL queries in your postman requests by selecting the GraphQL tab in the request Body.

POST Request in Postman

Here you need to enter the code in the section of QUERY and any variable in the section of GRAPHQL VARIABLES.

Cookies in Postman

Cookies are the files with very small size, which contain the information for server files or website pages. When you firstly open the website, a cookie file will be downloaded to your machine. This cookie contains some details; the same site can use the details when you visit again. This allows the website to offer a detailed response according to your last visit.

In postman, we can see the cookies that were sent as a response from the server. We cannot make any changes to the cookies since we got from the server.

Cookies Manager

To start the work on cookies in postman, open the Cookies option from the right side of the postman window under the Send button.

Cookies in Postman

When you select cookies, then it will open the Manage Cookies window. Here you can see the domains list and cookies linked with them.

In postman, we can also create new cookies for the domain. To create a new cookie, select the 'Add Cookie' button.

Here, I will take the www.google.com domain.

Enter the domain name in the URL text field and click on the Add button.

Cookies in Postman

Since we already have a google.com domain in the inventory, we will directly add the cookies. Click on '+Add Cookie.'

Cookies in Postman

A new text box will open where some default values are already written. Edit those values as given below example:

Cookies in Postman

Click on the Save button.

Cookies in Postman

Here you can see your newly created cookie.

Cookies in Postman

Close the panel. And enter the URL google.com in the URL text field and click on send. Go to the Response section and click on the Cookies tab. We can see the cookie which we have added here.

Cookies in Postman

In postman, we can update the cookies. Click on 'Cookies' to change an existing cookie and pick the domain from the domain list in the MANAGE COOKIES section, then click the cookie you want to update. We can change any property, and click Save to update.

Cookies in Postman

Deleting a cookie is very easy. To delete an existing cookie, click on 'Cookies,' and in the MANAGE COOKIES section, select the domain from the domain list, go to the cookie you want to delete, and click on X option. Your cookie will be deleted.

Cookies in Postman

Postman Intro to Collections

  • Collection in Postman means a group of API requests that are already saved in the Postman and can be arranged into folders. Any number of folders can be created inside a collection.

  • Putting similar requests into folders and collections helps the client in better organization and documentation of their requests.

  • All the APIs requests can be stored and saved within a collection, and these collections can be shared amongst the team in the Postman workspace.

Intro to Collections

Advantages of creating collections

  • Easy APIs import and export
    A collection can be imported or exported. Thus it can save time for transferring the requests.

  • Request categorization
    Requests can be grouped into folders and collections for easy access.

  • Passing data among requests
    Scripts can be used to pass data between API requests.

  • Running collections/folders.
    You can run individual requests or folder or collection as a whole in the Postman.

  • API documentation
    Postman provides you an option to add a name and description to your request, folder, and collections.

  • Building Test suits
    Test scripts can be added to requests, and integration test suites can be built.

  • Time-saving
    Setting any variable for collections will automatically apply the same to the folders generated under the collection and requests; thus, it saves time.

    Postman Creating Collections

    Creating a new collection

    A new collection can be created from the following options in Postman.

    1. New button in the Header bar

    • Go to New button in the header bar; click on Collection option.

      Creating Collections

    • A new window will pop up, as shown in the image below.

      Creating Collections

    • Name your Collection, and you can add an optional description.

    • Go to the authorization tab and select an authorization type.

    • Add a Pre-request script, which will execute before every request in this Collection.

    • Add tests, which will execute after every request in this Collection.

    • Add variables, which will be specific to this Collection and its requests.

    • Finally, click on the Create button, as shown in the image below, to save the Collection.

2. Collection tab in Sidebar

  • In the sidebar of Postman, click on the Collection tab and then select the New Collection option, as shown in the image below.

    Creating Collections

  • Again the same window will pop-up on the screen, then repeat the same procedure of authorization, variables, etc. to create the new Collection.

3. Create a collection option in the Launchpad

  • After you open the Postman app, in the builder section, you will get the launch pad.

  • In the launchpad, under the Start Something New tab, you will get Create a Collection option, as shown in the image below.

    Creating Collections

  • Once you click on Create a collection option, a new window will pop-up on the screen.

  • You will have to follow the same procedure of authentication, tests, variables, etc. as discussed earlier to create a new collection.

Saving a request to a collection

Whenever you create a new request in the Postman, you can save it as an individual request or in a new collection/folder or the existing collection/folder. You can create a new request from the following options, also mentioned in the image below.

Creating Collections

  1. New button in the sidebar

  2. Create a request option in the launch screen

  3. Builder section

  • Whichever option you choose to create the request, you will get the below-mentioned window to Save

    Creating Collections

  • Enter the request name, optional request description, and then select a collection or folder from 'select a collection or folder to save to' option, as shown in the image.

  • You can also create a new collection by clicking on +Create Collection.

  • Now click on the Save button to save the request.

Saving a request to a collection from history

To save the request from history to an existing or a new collection, follow the following procedure.

  • Go to the History tab in the sidebar of Postman then click on the (+) button to save the request. As given below:

  • A new Save Request window will pop-up on the screen, follow the same procedure and save the request to a new or existing collection.

    Creating Collections

Duplicating an existing collection

  • To duplicate a collection already saved in the Postman, go to the Collection tab of the sidebar.

  • Select the Collection that you want to duplicate, click on the (…) option to expand and click on Duplicate from the drop-down menu to duplicate the selected Collection.

    Creating Collections

Postman Sharing Collections

You can share your collections from the postman app to your workspace team and can also share it as a link to users who are not part of your workspace team. You need to sign-in to Postman to share a collection.

Users are not required to sign-in to the Postman account if they are sending collection as a file.

Steps to share collections in the app

Two options are available to share the collections.

1. From the Sidebar

  • Open the Postman app, go to the collection tab in the sidebar and click on (…) to extend and view more options as shown in the image.

    Sharing Collections

  • Click on the Share Collection option from the drop-down menu.

From Browse option

  • Switch to Browse by clicking on the Browse button available on the bottom right corner of the app, as shown in the image below.

  • Click on the Collections tab to see all your collections and select the Share option, as shown in the image.

    Sharing Collections

  • Whichever option you select to share your collections, a new window will pop-up on the screen with three options, as shown in the image below.

    Sharing Collections

  • So in Postman, you can share your collection in the following three ways.

Share to a Workspace

This option is used to share the collection with another workspace or with a member of the workspace. This will be available to all the members of the team if shared with a team workspace. However, after you shared the collection, you can change the permissions of collection from read-only to edit or vice-versa.

Now select the workspace team or member and select the share button to transfer the collection.

Share with Embed

With this option, as shown in the image below, you will get two buttons Run in Postman and Generate code. With the Generate code button, a link will be generated, and with Run in Postman button collection will be shared.

Sharing Collections

By this option, when you click on the Get Public Link button, a link will be generated, and with this link, your collection can be shared. Anyone who will have this link can access your collection, even the people outside your organization or team.

Sharing Collections

Sharing Collection as a file

Users are not required to sign-in to their Postman account if they are sending collection as a file. Simply download the collection in the form of JSON (JavaScript Object Notation) file and share it.

Variables in Postman

  • Postman variables work in the same way as that of the programming variables. These are the symbols capable of taking various values. You can store the values in variables and can use it throughout in requests, environments, collections, and scripts.

  • Variables in Postman increase the user's efficiency to work and decrease the errors.

Environment in Postman

A collection of key-value pairs is called an environment. Each name of the variable represents its keys. And referencing the name of the variable allows you to access its value.

It is a set of variables that differentiate among the requests. Such as, we can have an environment for testing, one for development and another for production. We can change the value of the variables to pass the data between requests and tests.

Creating an Environment

To create an environment, follow the following steps:

  • Go to New -> Environment.

    Variables in Postman

  • Or you can create an environment from Environment quick look. For that, click on Environment quick look button visible as an eye icon available in the top right corner of the builder section, as shown in the image below.

    Variables in Postman

Now select Add.

Variables in Postman

Enter the name of the Environment and click on Add.

Variables in Postman

We can also download, share, delete, duplicate, or import the environment.

Variables in Postman

Sharing an environment will help you to run your requests against the same set of data.

Environment Variable in Postman

The postman variable is similar to the programming language variable. As we know, a variable is an entity, which stores value. You can change the value of the variable. In Postman, a variable is a set of key-value pairs. Here the key is the variable and value is the value of the variable.

Creating an Environment Variable in Postman

To create an environment variable follow the following steps:

  • Go to Environment quick look button visible as an eye icon available in the top right corner of the builder section.

    Variables in Postman

  • Select the Edit option.

    Variables in Postman

  • Enter the below mentioned key-value pairs in which Key = url and Initial Value = http://restapi.demoqa.com

    Variables in Postman

Then select the Update button and close the Manage Environment window. Now you have an environment variable with the name 'url', and the value of the variable is the http://restapi.demoqa.com.

Using an Environment Variable in Postman

  • Select the environment from the drop-down. Now we can access the entire available variable in the environment.

    Variables in Postman

  • In the address bar or we can say URL text field enter the following url: {{url}}/utilities/weatherfull/city/Bengaluru

    Variables in Postman

  • Click on send. You will get the following response:

    Variables in Postman

So, the environment is created with a variable named "url". This means we can now use the variable instead of the actual URL.

Global Variables in Postman

Here we will see how to create global variables. Unlike the environment variable, in the case of global variables, we don't need to create an environment first.

Creating a Global Variable in Postman

  • Open the Postman app and click on Environment quick look button visible as an eye icon available in the top right corner of the builder section, as shown in the image below.

    Variables in Postman

  • Now select Edit option as shown in the image below available next to Globals.

    Variables in Postman

  • Enter the below mentioned key-value pairs in which Key = url and Initial Value = restapi.demoqa.com

    Variables in Postman

  • Select the save button and close the Manage Environments Here your global variable is created with the name 'url'.

Using a Global Variable in Postman

Select the No Environment from the drop-down of Postman, from the top right corner of Postman.

Variables in Postman

  • In the address bar enter the following url: {{url}}/utilities/weatherfull/city/Bengaluru

    Variables in Postman

  • Click on Send and see the response.

    Variables in Postman

Variable Scopes

Variable scope is the boundary within which these variables can be accessed and executed. The following variable scopes are supported by Postman, which is used for different tasks. The narrowest variable scope is Local, and then next is Data, Environment, Collection, and the broadest one is Global.

Variables in Postman

In case, the variable name is the same, in two scopes with a different value, then the value of the narrowest variable scope will be used while running the request. Let's say the name of both local and global variables is My Variable. Then Postman will use a local variable value to run the request, as a local variable is the narrowest variable scope.

Let's see these variable scopes one by one:

  • Local Variables
    These are temporary variables that will only function inside the environment they were created in. When you change the environment, the variable will stop its access, and an error will occur.

  • Collection Variables
    These are independent of environments and are available for all the requests in a collection.

  • Environment Variables
    These are the most used variable scope in Postman. At a time, a single environment can be active. They are bound to a specified environment used to execute the request.

  • Global Variables
    These are independent of environments and function outside the environment. Users are not required to create an environment for global variables. Through global variables, we can access data between collections, test scripts, requests, and environments.

  • Data Variables
    Data variables come from external CSV(Comma seperated value) and JSON files to define data sets that you can use while collections are running through Newman or the Collection Runner.

    Postman Dynamic Variables

    Dynamic variable, as the name suggests, generates random data to your API requests and collection run. It is like a random library in a programming language. It generates random data each time in response like a random number, alphabets, alphanumeric or color, etc.

    A dynamic variable name starts with '$.' In the request URL section, a dynamic variable should be written in {{__}} format.

    Let's say you have to pass an integer number from 1 to 1000, so for that, you need to add {{$randomInt}}.

    Like the above example of the number variable, Postman supports so many other dynamic variables as well.

    Some important Dynamic Variables are

    Numbers, Texts and Colors

    | Variable Name | Description | | --- | --- | | $randomAlphaNumeric | A random alphanumeric character | | $randomInt | A random integer between 1 and 1000 | | $randomColor | A random color | | $randomHexColor | A random hex value | | $randomAbbreviation | A random abbreviation | | $randomBoolean | A random boolean value like true or false |

    Address, Location, Phone

    | Variable Name | Description | | --- | --- | | $randomCountry | A random country | | $randomCountryCode | Random country code of two letters (ISO 3166-1 alpha-2) | | $randomCity | A random city name | | $randomStreetName | A random street name | | $randomStreetAddress | A random street address | | $randomLatitude | A random latitude coordinate | | $randomLongitude | A random longitude coordinate | | $randomPhoneNumber | A random 10-digit phone number | | $randomPhoneNumberExt | A random phone number with an extension of 12 digits |

    Profession

    | Variable Name | Description | | --- | --- | | $randomJobType | A random job type | | $randomJobTitle | A random job title | | $randomJobDescriptor | A random job descriptor | | $randomJobArea | A random job area |

    Names

    | Variable Name | Description | | --- | --- | | $randomFullName | A random first and last name | | $randomNamePrefix | A random name prefix | | $randomNameSuffix | A random name suffix | | $randomFirstName | A random first name | | $randomLastName | A random, last name |

    Dates

    | Variable Name | Description | | --- | --- | | $randomWeekday | A random weekday | | $randomMonth | A random month | | $randomDateRecent | A random recent datetime | | $randomDateFuture | A random future datetime | | $randomDatePast | A random past datetime |

    Databases

    | Variable Name | Description | | --- | --- | | $randomDatabaseType | A random database type | | $randomDatabaseCollation | A random database collection | | $randomDatabaseColumn | A random database column name |

    Domains, Username, and Emails

    | Variable Name | Description | | --- | --- | | $randomUrl | A random URL | | $randomUserName | A random username | | $randomEmail | A random email address | | $randomDomainName | A random domain name | | $randomDomainSuffix | A random domain suffix |

    Internet and IP address

    | Variable Name | Description | | --- | --- | | $randomIP | A random IPv4 address | | $randomIPV6 | A random IPv6 address | | $randomPassword | A random alphanumeric password of 15-character | | $randomUserAgent | A random user agent | | $randomProtocol | A random internet protocol | | $randomMACAddress | A random MAC address |

    Files and Directories

    | Variable Name | Description | | --- | --- | | $randomCommonFileName | A random file name | | $randomFileName | A random file name (includes uncommon extensions) | | $randomFileExt | A random file extension (includes uncommon extensions) | | $randomFileType | A random file type including uncommon file types | | $randomCommonFileType | A random, common file type | | $randomCommonFileExt | A random, common file extension | | $randomDirectoryPath | A random directory path |

    Images

    | Variable Name | Description | | --- | --- | | $randomImage | A random image | | $randomImageUrl | A URL for a random image | | $randomAnimalsImage | A URL for a random animal image | | $randomCityImage | A URL for a random city image | | $randomFoodImage | A URL for a random food image | | $randomTransportImage | A URL for a random transportation image | | $randomSportsImage | A URL for a random sports image | | $randomTechnicsImage | A URL for a random tech image |

    Business

    | Variable Name | Description | | --- | --- | | $randomCompanyName | A random company name | | $randomCompanySuffix | A random company suffix (e.g., Inc, LLC, Group) | | $randomBs | A random phrase of business-speak |

    Finance

    | Variable Name | Description | | --- | --- | | $randomCurrencyName | A random currency name | | $randomCurrencySymbol | A random currency symbol | | $randomCurrencyCode | A random 3-letter currency code (ISO-4217) | | $randomBitcoin | A random bitcoin address | | $randomTransactionType | A random transaction type (e.g., invoice, payment, deposit) | | $randomBankAccount | A random bank account number of 8-digit | | $randomBankAccountName | A random bank account name (e.g., savings account, checking account) |

SCRIPT

Intro to Scripts

Postman is not only used for manual testing, but we can also do automation testing of API. Postman requests and collections can be applied to dynamic behavior.

In Postman Scripts are the lines of code that allow you to automate an API test. It offers you to write pre-request and test scripts.

  • Before sending a request, a pre-request script will run and,

  • After receiving a response, test scripts will run.

In Postman, we can write the tests, pass the data between the requests, and change the parameters. It allows adding test script and pre-request script to a collection, a folder, a request, or a request not attached to a group.

Postman Sandbox

To write the script in Postman, we use Postman Sandbox.

Postman sandbox has been written in Javascript. It is an execution environment. Since the sandbox has written in Javascript, therefore, it will only receive a script written in Javascript.

Hence, we have to write the script in javascript to make the code executable in Postman.

Execution Order of Scripts in Postman

In Postman, the order of script execution for a single request is as follows:

Intro to Scripts

  • A pre-request script associated with a request will execute before sending the request.

  • Test script associated with a request will execute after sending the request.

The order of script execution for every request in a collection is as follows:

Intro to Scripts

  • Before every request in the collection, a pre-request script associated with a collection will run.

  • Before every request in the folder, a pre-request script associated with a folder will run.

  • After every request in the collection, a test script associated with a collection will run.

  • After a request in the folder, a test script associated with a folder will run.

The scripts should always run according to the following hierarchy for every request in a collection:

  • Collection level script

  • Folder level script

  • Request level script

The same order will be applied for both pre-request and test scripts.

Pre-request Scripts

Pre-request scripts are a piece of code that will run before the execution of a request. It runs in the Postman sandbox and allows us to add dynamic behavior to request execution.

We can apply the pre-request scripts at a request level, a collection level, or a folder level, which means that a pre-request script will apply to all the requests that are part of that collection or folder.

However, if we have defined scripts in all three means in the request, collection and folder, then the script must run in a given order:

  • A pre-request script associated with a collection will run before any request in the collection.

  • A pre-request script of a folder will run before any request in the folder.

We can use the pre-request script for a pre-processing task like setting parameters, variable values, body data, and headers. We may also use pre-request scripts to debug the code, such as by logging output to the console. Also, using the concept of the pre-request script, we can get the output of the function such as date, time, timestamp, etc.

Let's look at a simple example to prove that pre-request scripts are running before a request is executed:

  • Click on the postman console. Postman console stores all the things that happen in the request. Through the postman console, we can see the logs and errors. It is like browsers development console in which all the things are visible, including whole requests that users have sent to that website or to the page code.

  • To open the postman console, select the "Postman Console" icon from the bottom of the window or press ctrl+alt+c.

Pre-request Scripts

Clear the old logs from the console.

Pre-request Scripts

  • Now, enter the URL in the URL text field.

Pre-request Scripts

  • Go to the Pre-request Script tab and write the following script:
  1. console.log ("This is a pre-request script")  

Pre-request Scripts

  • Press the Send button and check the postman console.

Pre-request Scripts

Here, you can see that the pre-request script is running prior to the request execution.

Creating Variables by Pre-request Script

Here, we will use the environment variable.

  • Go to Environment quick look button visible as an eye icon available in the top right corner of the builder section.

Pre-request Scripts

  • Select your environment from the drop-down. Here we will use Development API that we have already created while learning about 'Variables in Postman'.

Pre-request Scripts

  • In the address bar enter the following url: {{url}}/utilities/weatherfull/city/Bengaluru

Pre-request Scripts

  • Go to the Pre-request Script Write the following code inside the editor:
  1. postman.setEnvironmentVariable('username','Nikita');

Pre-request Scripts

This will create a variable inside the "Development" environment with the name "username" and value "Nikita".

  • Select the Send button and look at the current variable by selecting the Environment quick look button visible as an eye icon.

Pre-request Scripts

Here, we can see the created "username" variable available in the environment.

Similarly, add the following script in the pre-request script editor:

  1. postman.setEnvironmentVariable('Tutorial','Javatpoint');

Pre-request Scripts

Again check the Development environment variable:

Pre-request Scripts

Hence, we can perform multiple tasks in the pre-request script before script execution without going through the process of creating and deleting variables again and again.

Test Scripts

Test scripts execute after the server receives the response. In postman, we can write test scripts to test API requests in Javascript. Test script is used to test whether your API is working accordingly or not, to establish that integrations between the services are functioning properly, and to check that new developments have not affected any functionality of existing requests. Test Scripts are also called Post-Request script.

We can use the test code to debug the process of your API project. Such as, you may use the test script to verify error handling for your API by submitting an incomplete data request.

We can run the test scripts to a single request, folders, or collections. Let's see a simple example to add the test script to a request:

  • Open the postman console. To open the postman console, select the "Postman Console" icon from the bottom of the window or press ctrl+alt+c.

Test Scripts

Clear the old logs from the console.

Test Scripts

Now, enter the URL in the URL text field.

Test Scripts

  • Go to the Tests tab and write the following script:
  1. console.log ("This is a tests script")
  • Press the Send button and check the postman console.

Test Scripts

Here, you can see that the test script is running after the request execution.

Creating Variables using Tests Script

Here, we will use the environment variable.

  • Go to Environment quick look button visible as an eye icon available in the top right corner of the builder section.

Test Scripts

  • Select your environment from the drop-down. Here we will use Development API that we have already created while learning about 'Variables in Postman'.

Test Scripts

  • Now, enter the given URL in the URL text field. {{url}}/utilities/weatherfull/city/Bengaluru

Test Scripts

  • Go to the Tests Write the following code inside the editor:
  1. pm.environment.set("u", "Hello");

Test Scripts

This will create a variable inside the "Development" environment with the name "u" and value "Hello".

  • Select the Send button and look at the current variable by selecting the Environment quick look button visible as an eye icon.

Test Scripts

Here, we can see the created "u" variable is available in the environment.

Writing Test Scripts

We can enter the script manually or use the Snippets, which is available on the right side of the code editor.

Test Scripts

Test Scripts

We can also write our custom test script in Postman. Postman offers a 'pm' API (called as pm.* API), which is used to write the tests.

pm.test()

This function writes the conditions of the test in the postman test sandbox. Writing tests within this feature helps you to correctly name the test and ensure that the rest of the script is not interrupted in case of any errors.

This function has two arguments, first is the test name (as a string), and second is a function which returns a Boolean value.

Let's see an example:

  • Enter any URL in the URL text field.

Test Scripts

  • Enter the following script in Tests tab:
  1. // example using  pm.response.to.have  

  2. pm.test("response is ok", function () {  

  3. pm.response.to.have.status(200);  

  4. });

Test Scripts

Click on the Send button to test your request and select Test Results in the response section. This will show how many tests passed and how many ran in total.

Test Scripts

In the above example, if the request returned a 200 status code, the test will pass; otherwise, it will fail. Try to change the status code of your tests and run the same request again.

  1. pm.test("Status Fail", function () {

  2. pm.response.to.have.status(404);

  3. });

Test Scripts

You will get the following response:

Test Scripts

pm.except()

The pm.except() function is used to print the test result messages in a different format. This function makes the test readable, and even we can manage data assertions from a variable or response.

  1. // example using pm.expect()  

  2. pm.test("Status", function () {   

  3.     pm.expect(pm.response.code).to.equal(404);   

  4. });  

Test Scripts

Click on the send button and see the Test Results from the response section:

Test Scripts

Through this function we can test the request environment, as given below:

  1. pm.test("environment to be production", function () {

  2. pm.expect(pm.environment.get("env")).to.equal("production");

  3. });

Another example is:

  1. // example using response assertions

  2. pm.test("Status Ok", function () {

  3. pm.response.to.not.be.error;

  4. pm.response.to.have.jsonBody("");

  5. pm.response.to.not.have.jsonBody("error");

  6. });

pm.response.to.be.*

This is an object, offers shorthand for the tests based on commonly used response.

  1. // example using pm.response.to.be*

  2. pm.test("Response", function () {

  3. // assert that the status code is 200

  4. pm.response.to.be.ok;

  5. pm.response.to.be.withBody;

  6. pm.response.to.be.json;

  7. });

Test Results

To test written tests are passing or failing; we use Test Results. Once you run a request with tests, then select the Test Results tab from the response window. Here, you will get a list of your test results, whether the test has passed or failed. A test with Boolean value true means a passing test, and false means test is failing.

Test Scripts

Test Examples

As we understood from the previous section, Test scripts are executed after a request has been sent, and the server has received a response.

Here, we will discuss some examples of tests. Most of the examples are available in the snippets of the Postman. We can run multiple tests for a single request.

Environments

Setting an Environment Variable

  1. pm.environment.set("variable_key", "variable_value");

Test Examples

We can also set a nested object as an environment variable:

  1. var array = [1, 2, 3, 4];

  2. pm.environment.set("array", JSON.stringify(array, null, 2));

  3. var obj = { a: [1, 2, 3, 4], b: { c: 'val' } };

  4. pm.environment.set("obj", JSON.stringify(obj));

Getting an Environment Variable

  1. pm.environment.get("variable_key");

Test Examples

Clear an Environment Variable

  1. pm.environment.unset("variable_key");  

Test Examples

Collection

Setting a Collection Variable

  1. pm.collectionVariables.set(variableName:String, variableValue:String);

Get a Collection Variable

  1. pm.collectionVariables.get(variableName:String);  

Clear a Collection Variable

  1. pm.collectionVariables.unset(variableName:String);  

Globals

Setting a Global Variable

  1. pm.globals.set("variable_key", "variable_value");  

    1. pm.globals.unset("variable_key");  


Test Examples

Response Handling

Search for a String in Response Body

  1. pm.test("Body Contains", function () {  

  2.     pm.expect(pm.response.text()).to.include("search_string");  

  3. });  

Check if Response Body is equal to a String

  1. pm.test("Body is correct", function () {  

  2. pm.response.to.have.body("response_body_string");  

  3. });  

Check for a JSON Value

  1. pm.test("Your test name", function () {  

  2.     var jsonData = pm.response.json();  

  3.     pm.expect(jsonData.value).to.eql(100);  

  4. });  

Check if Content-Type header is present

  1. pm.test("Content-Type header is present", function () {  

  2. pm.response.to.have.header("Content-Type");  

  3. });  

Response Time is less than 200 ms

  1. pm.test("Response time is less than 200ms", function () {  

  2.     pm.expect(pm.response.responseTime).to.be.below(200);  

  3. });  

Status code is 200

  1. pm.test("Status code is 200", function () {  

  2. pm.response.to.have.status(200);  

  3. });  

Code name contains a string

  1. pm.test("Status code name contains a string", function () {  

  2. pm.response.to.have.status("Created");  

  3. });  

Successful POST request status code

  1. pm.test("POST request Successful ", function () {  

  2.     pm.expect(pm.response.code).to.be.oneOf([201,202]);  

  3. });  

Test Examples

Getting a Global Variable

  1. pm.globals.get("variable_key");

Test Examples

Clear a Global Variable

  1. pm.globals.unset("variable_key");

Test Examples

Response Handling

Search for a String in Response Body

  1. pm.test("Body Contains", function () {  

  2.     pm.expect(pm.response.text()).to.include("search_string");  

  3. });  

Check if Response Body is equal to a String

  1. pm.test("Body is correct", function () {  

  2. pm.response.to.have.body("response_body_string");  

  3. });  

Check for a JSON Value

  1. pm.test("Your test name", function () {  

  2.     var jsonData = pm.response.json();  

  3.     pm.expect(jsonData.value).to.eql(100);  

  4. });  

Check if Content-Type header is present

  1. pm.test("Content-Type header is present", function () {  

  2. pm.response.to.have.header("Content-Type");  

  3. });  

Response Time is less than 200 ms

  1. pm.test("Response time is less than 200ms", function () {  

  2.     pm.expect(pm.response.responseTime).to.be.below(200);  

  3. });  

Status code is 200

  1. pm.test("Status code is 200", function () {  

  2. pm.response.to.have.status(200);  

  3. });  

Code name contains a string

  1. pm.test("Status code name contains a string", function () {  

  2. pm.response.to.have.status("Created");  

  3. });  

Successful POST request status code

  1. pm.test("POST request Successful ", function () {  

  2.     pm.expect(pm.response.code).to.be.oneOf([201,202]);  

  3. });  

Workflows in Postman

POSTMAN workflow is the order of request execution within a collection. When you run the collection directly, then the requests are either executed randomly or executed serially. But we can also set the priority of the request, and we can also choose the order of execution of request means we can set which request should be executed when. This feature is called workflow in Postman.

Postman provides a feature to control the workflow of requests in the collection, and the feature is called Collection Runner (or Runner).

Once a request is executed by the collection runner, all requests within the collection are executed, but there is a pattern in which all requests are executed. Postman provides many inbuilt algorithms to decide in which pattern the request has to be run.

Order of Execution of Collection Runner

Generally, the collection runner runs the request in sequential order. Some APIs requires to send request one by one; means, the second request that can execute only after the first request has completed and the third request will wait for the response of the second request. And so on.

In this case, the default request execution in the collection runner is fine, as there is no requirement to run the requests parallelly, or no random request has to be run.

But there may be cases where one API request can be dependent on two or more different API response. Or there may be another situation where a particular API request which is in the middle of the APIs request execution queue, have to get executed for different request randomly.

In this case, the sequential execution of the request in the collection runner will not be useful. We should have to create a workflow and inform the collection runner that, which requests to execute when. This task can only be done by calling an API request. This is called an API call.

An API call means calling an API for its execution in a user-defined manner.

Default Workflow in Postman

Let's see how the normal request execution workflow runs in default.

  • Create a collection and give the name of the collection. Here my collection name is "Default Workflow."

Workflows in Postman

  • Add three requests in the collection and name it as Request 1, Request 2, Request 3.

Workflows in Postman

  • Three requests are:

Workflows in Postman

Add the following URL in-

Request 1: www.javatpoint.com

Request 2: www.google.com

Request 3: www.facebook.com

  • Now you have three different requests in a collection. Run the collection runner now.

Select the Runner (Collection Runner) menu from the top of the postman window. It will open a new window.

Workflows in Postman

  • Choose your collection.

Workflows in Postman

  • Run the collection to see all the iterations, orders, environments, etc. for the collection.

Workflows in Postman

Workflows in Postman

Now in the above image, you can see the request is sent sequentially. It starts with the Request 1, and then continues to Request 2 and then Request 3. This means it is running sequentially.

Asserts in Postman

The assertion checks whether the given predict is true or false in any programming language. A predict is a Boolean expression with the value true or false. That means assertion is nothing but code that can be used to check or analyze the response that is received from the server.

An assertion is a code written in javascript in Postman that is executed after receiving the response.

Why we use Assertion in Postman

The main purpose of the test is to determine whether a given parameter of the system is working or not. To apply the force on the function parameters, we assert the predicted values during a test run with the actual values.

Assertions help us to assert that expected and actual values should match during a test run. If the actual and expected values don't match, then the test will fail with the output pointing to the failure.

In Postman, we can write the assertion in many ways. One of the simplest ways is the snippets, which are nothing but a block of codes that have some unique functions inside it and are available in the postman app. Users can easily access the snippets and can get the code inside the tests editor and run the test.

Example

Here we will discuss assertions that are primarily based on responses in the format of .json.

In Postman, an assertion can be applied on different attributes such as an object, arrays, etc.

As we know by default in Postman, the received response from the server is displayed in the JSON format, or even we can select the JSON application and get the response converted into the JSON format.

First of all, enter the following URL in the URL text field:

https://reqres.in/api/users?page=2

Send the request and see the response:

Asserts in Postman

Now add the following line of code in the test tab of the given request.

  1. let jsonData = pm.response.json();

  2. console.log(jsonData.data);

Asserts in Postman

The code pm.response.json() is used to parse the JSON body. And console.log(jsonData.data) code is used for logging the object into the Postman console.

Now, return the request and open the postman console.

Asserts in Postman

In the above image, you can see the arrays inside the object. Various objects are listed numbered from 0 to 5, so there were six different objects.

We can access the name and value of the array with the help of the dot (.) operator.

Edit the tests editor with the following line of code and see the console:

  1. let jsonData = pm.response.json();

  2. console.log(jsonData.data[2].id);

Asserts in Postman

Asserts in Postman

Here, you can see the value of the id, which belongs to index 2 of the array.

Chai Assertion Library

Chai assertion library is an external javascript library used to write assertions. Compared to what we write directly in javascript, this assertion library needs less time & effort and easy use.

Chai assertion library is available by default in the Postman. So when you are writing chai assertions, then don't worry about other processes of installation. The main feature of Postman assertions is that they write the tests with English sentences, which is human readable. So it is very easy to read and user friendly.

Chai Assertion Library

If you would like to learn more about the Chai Assertion Library, there is an official website for that. You can visit this chaijs.com.

Writing Assertions using Chai Assertion Library.

Copy the following URL in the URL text field.

  1. www.javatpoint.com

Example 1:

  • Go to the Tests tab and write the following code in the Tests editor.
  1. pm.test("If 100 equal to 200", function(){

  2. pm.expect(100).to.eql(200);

  3. });

Chai Assertion Library

  • Click on Send and see the Test Results from the response section.

Chai Assertion Library

In the above example, we are checking that if 100 is equal to 200 or not. The response is failed, which is obvious.

Just edit the code with the following code and see the response again.

  1. pm.test("If 100 equal to 100", function(){  

  2.     pm.expect(100).to.eql(100);  

  3. });  

Chai Assertion Library

Chai Assertion Library

Since 100 equal to 100. The test is passed.

Example 2:

Here, we will check the given number is in an array or not.

  • Open the tests tab and write the following code:
  1. pm.test("Number included", function(){  

  2. pm.expect([100,200,300]).to.include(300);  

  3. });  

Chai Assertion Library

  • Press send and see the Test Results tab from the response.

Chai Assertion Library

Here, you can see that the test is passed because, in the array list of 100, 200, and 300 has 300.

Example 3:

In this assertion, we will verify the object.

  • Open the tests tab and write the following code:
  1. pm.test("Compare Name", function(){

  2. let x= {

  3. "name" : "Nikita"

  4. };

  5. let y= {

  6. "name" : "Nikita"

  7. };

  8. pm.expect(x).to.eql(y);

  9. });

Chai Assertion Library

  • Click on the Send button and see the Test Results from the response.

Chai Assertion Library

The test is passed because on both objects, names are equal.

In the above code, we have used eql(). Postman offers both methods eql() and equal(). But both methods are different. equal() is used to compare the objects, and eql() is used to compare the properties of the objects. In this case, eql() compared the name property of the object.

Try to edit the last line of code with pm.expect(x).to.equal(y), and see the response.

Chai Assertion Library

Chai Assertion Library

The above test failed because we have used equal(), which compares the object, not the property of the object.

MOCK SERVERS

Intro to Mock Servers

  • The mock server is a fake server that simulates as a real server to help the users for testing and checking their APIs and APIs responses.

  • During the various API testing, a Mock server is used when specific responses are required to be received that are not readily available on the web servers or for certain testing, which cannot be done due to security issues on real servers.

How Mock Server Works

When you send the request then MockServer receives that request, it matches the request against the specified requirement, and if no matches are found, it will proxy the request, if possible. The request would otherwise return a 404.

For each Received Request:

  • Find matching expectations and perform an action.

  • If the request does not match the expectation, then it will proxy request.

  • if not a proxy request will return 404

Here the expectation is the action being taken, which could be returned to a response.

Types of Mock Servers

We can create two types of Mock Servers in Postman:

1. Private mock server

These cannot be accessed by everyone. When you create a private mock server, users may share the collections with their teammates lying under it. Your team may use the mock by adding API keys in the request header x-api-key, like x-api-key:<your postman API key>.

2. Public mock server

Public mock servers are open to all. When you share this mock server, users are not required to add a Postman API key to consume the mock.

Benefits of Postman Mock server

  • To check your own API during development and before you make that API live on your organization's server.

  • To get faster reviews and bugs.

  • Without any authentication, any type of request can be made into the server.

  • To test the dependencies inside the API until they are open to everyone.

  • For QA engineers, use this to check or isolate external dependencies and check the integration.

  • Using it before actual endpoints are available by front end developers.

  • A mock server is used by engineers to create a prototype of their idea to submit it for funding to the investors.

    Setting Up a Mock Server

    To set up a mock server in Postman, we will need a collection because mocks in Postman are tied with a collection. Postman compares the requests and creates mock responses from the examples in the requests of a collection.

    Before creating a Mock server in Postman, there are some important points about the mock server we must know:

    • In the Postman app, the mock server is already integrated, so we don't need to waste the time to download and install externally.

    • The mock server supports CORS. CORS stands for Cross-Origin Resource Sharing. When using the mock server, it ensures you that you won't get any cross-origin errors.

    • The mock server is available in Postman, which is free to use.

In Postman, there are many ways to build a mock server:

  • New Button

  • Postman API

  • Launch Screen

  • Postman App

By default, the mocks are open to using. It is accessible publicly. When you make a private mock server, enterprise users and postman pro clients can share the underlying collection with their group and particular team members, or they can give permissions to edit or view.

Let's create the mock server. Here we will discuss how to create a mock server with the New button.

  • From the top left corner in the Header section of the Postman app, select the New button.

Setting Up a Mock Server

  • Select the Mock Server.

Setting Up a Mock Server

  • Once you select the Mock server, a new panel will be opened. Through this panel, we can create a new request.

Setting Up a Mock Server

In the above image, we have multiple options.

Here,

  • The method is request type methods such as GET, POST, etc.

  • Request Path is the URL of the request for your API.

  • Response Code is the code in which we want to get in response.

  • Response Body is the body of the response that you want to show in response.

Fill the column as given below:

Setting Up a Mock Server

  • Click on Next. Now on the next tab, give the name of your mock server. You can give anything as per your choice.

Setting Up a Mock Server

In the above image, you can see one checkbox. If you want to make your mock server private, enable it.

Select the Create Mock Server button.

  • The next panel is the review panel, which gives you the review that your mock server has been successfully built.

This screen will also display an URL through which we can access the mock server.

Setting Up a Mock Server

  • Click on the Close button to close the panel.

Once you close the panel, a new collection has been generated with the given APIs.

Setting Up a Mock Server

  • We can also see a new environment has been created with the same name.

Setting Up a Mock Server

Select this environment variable.

  • Now, choose the first request from the collection and see the request url.

Setting Up a Mock Server

  • Click on the send button. Here you can see the response.

Setting Up a Mock Server

Here, you can see, we got the same response body and the same response code as we have created while setting up the mock server.

Get the Response in Mock Server

Here we will discuss how to get the response in other different formats in Postman, which is very easy. The most common format is JSON. Let's see how to get the response in JSON format.

  • From the top left corner in the Header section of the Postman app, select the New

Get the Response in Mock Server

  • Select the Mock Server.

Get the Response in Mock Server

  • Once you select the Mock server, a new panel will be opened. Through this panel, we can create a new request.

Get the Response in Mock Server

  • In the Response Body column, instead of writing plain text, enter the response body in JSON format.

Here, we will write the data about different Employees:

  1. {

  2. "Employees" [

  3. {

  4. "Id": "101",

  5. "Name": "Nikita Kesharwani",

  6. "DOB": "12-12-1992",

  7. "Father's Name": "John E. Silverman",

  8. "Blood Group": "O+",

  9. "Contact Number": "999912345",

  10. "Address": "Cartridge World Bradford 212 Manningham Lane BD8 7DT Bradford RShaw Limited T/A Cartridge World",

  11. },

  12. {

  13. "Id": "102",

  14. "Name": "Senthil Gonzaleaz",

  15. "DOB": "24-06-1989",

  16. "Father's Name": "Richard O. Locher",

  17. "Blood Group": "AB+",

  18. "Contact Number": "+636312749",

  19. "Address": "Alina Business & Financial Services 61 High Street SE25 6EF London Alina Business & Financial Services",

  20. }

  21. ]

  22. }

Copy the above JSON in the Response body.

Get the Response in Mock Server

  • Press Next. Now in the next panel, give the name of the server as per your choice. I gave 'JSON Response'.

Get the Response in Mock Server

  • Select on Create Mock Server button.

Get the Response in Mock Server

  • Select the Employee API and then select the JSON Response environment.

Get the Response in Mock Server

  • Press send and see the response.

Get the Response in Mock Server

Here, you might get the response in HTML format by default, change the format to JSON from the dropdown, and you will get the response as given above.

  • Similarly, we can use different formats to get the response in a mock server.

    POSTMAN API

  • Introduction to Postman API

    The endpoints of the Postman API allow you to integrate Postman into your toolchain for development.

    In postman API, we can create new collections, update environments, update existing collections, and directly add and run monitors. It helps you to access the stored data programmatically in your postman app.

    Generating a Postman API Key

    It is necessary to have an applicable API key to send the request.

Introduction to Postman API

  • Choose your workspace.

Introduction to Postman API

  • Select the Integrations tab and locate the Postman API and then select View Details.

Introduction to Postman API

  • You will get the Generate API Key option if you don't have any keys yet. Select the Generate API Key

Introduction to Postman API

  • Enter the name of the key as per your choice and click on Generate API Key. Here I gave 'user-development-key'.

Introduction to Postman API

  • Don't forget to copy the key. Then click close.

Introduction to Postman API

  • Your key has been generated. You can now handle the keys within your workspace.

Introduction to Postman API

  • You can delete and regenerate the key.

Introduction to Postman API

  • Select on API Key Settings option to set the expiration period of your key.

Introduction to Postman API

Authentication

By submitting your API Key in the X-Api-Key header of any of your created requests, you will need to authenticate your requests to the Postman API.

  • This API key is used to give access to authorized data.

    You can also store your API key in an environment variable with the name postman-api-key. The Postman API collection can access the API key automatically.

    Rate Limits

    60 requests per minute are required to access the API with the key.

    Each response of an API contains the following set of headers to identify your consumption status.

    | Header | Description | | --- | --- | | X-RateLimit-Limit | This header specifies the maximum number of requests the consumer is allowed to submit per minute. | | X-RateLimit-Remaining | This header specifies the number of requests that are left in the current limit window. | | X-RateLimit-Reset | This header defines the time at which the current rate limit window resets in UTC epoch seconds. |

    CONTINUOUS INTEGRATION

  • Continuous Integration is also known as CI. It is a development method that is required several times a day by developers to integrate the code into a shared repository.

    Each check-in process involves automating the build and allowing teams to detect problems early. By integrating regularly, we can quickly detect errors, and locate the errors very easily.

    To run within your CI environment, let's use collections from Postman API.

    Some pre-requisites are:

    • It would be best if you had a system set up with Continuous Integration that can execute shell commands and have access to change the same.

      • You should have an API key.

      • It requires a postman collection that can check your local server, and note the collection UID.

Follow the following steps:

1. Install Node

If your CI already have Node installed, you can skip this stage.

Some CI has, by default, installed Node. If your CI has no node, then open this link and follow the steps to install the Node on your CI's platform. Make sure you have NodeJS v4 or above.

2. Install Newman

In Postman, Newman is a command-line collection runner tool that lets you run a collection on your server or in your local development environment.

To install the Newman use the given command:

  1. npm i newman -g;

3. Execute Newman

To execute the Newman, use the below command:

  1. newman run  api.getpostman.com/collections{{collection_uid}}?apikey={{postman-api-key-here}}

The above command is the syntax to run a newman. Change the parameters accordingly.

If you want to modify an environment to the collection, use the given command instead of above command:

    1. newman run  api.getpostman.com/collections{{collection_uid}}?apikey={{postman-api-key-here}}

      1. --environment  api.getpostman.com/environments{{environment_uid}}?apikey={{postman-api-key-here}}

        Branching and Looping

        In Postman, we can also work on branching and looping. We can branch and loop across API requests with the help of setNextRequest() function.

        1. postman.setNextRequest("request_name");

This function is used to set the request to be executed next. This function takes one argument, i.e., the name of the request, which will execute next.

Branching and Looping

In the above example, "My API" is the name of the request.

Some features of setNextRequest():

    • Provide the request name or request ID, and the collection runner will handle the rest.

      • We can use the setNextRequest() in the test script as well as in the pre-request script. The last set value takes precedence when you have more than one assignment.

      • The collection runner will follow the linear execution settings from default settings and moves to the next request if Postman.setNextRequest() isn't given in a request.

Loop Over the Current Request

If you give the currently running request name in the argument of setNextRequest() function, then Postman will run the same request continuously.

Branching and Looping

But when you are continuously looping along with the same request, we have to apply some logic on setNextRequest() so that the request won't run endlessly; the collection runner will otherwise have to be force closed.

Stop Workflow Execution

To stop the execution of workflow pass the null argument in setNextRequest() function.

  1. postman.setNextRequest(null);