Postman Beginner's Course - API Testing

Postman Beginner's Course - API Testing

Introduction

In this section, the instructor introduces themselves and the course. They explain what Postman is and why it's important for API testing.

What is an API?

  • An API is essentially an interface to a server that has some data or does some actions.
  • To use an API, we need to know and follow the specification.
  • APIs share a similar concept to power outlets in our homes.

What is Postman?

  • Postman is a tool for interacting with web-based APIs that work over the internet.
  • It helps us connect to an API and makes sure that the process of sending and receiving data is much easier.
  • There are two ways of running Postman: in your browser by going to postman.com or as a standalone app that you have to download and install.

Using an API in Postman

  • Before using an API, we need to understand how to interact with it by looking at its documentation.
  • The instructor demonstrates how to use the status endpoint of the book ordering API they will be using throughout the course.

Installing Postman

In this section, the instructor explains how to install Postman on your computer.

Installation Instructions

  • Go to postman.com and sign up for an account.
  • Follow the setup instructions which are relatively easy.
  • There are two ways of running Postman: in your browser by going to postman.com or as a standalone app that you have to download and install.

Updating Postman

  • Postman is actively developed so there may be slight differences from what you see in this video when you use it later on.
  • The principles stay the same, but if there's something really important you need to know, check for updates in the course notes.

Understanding API Documentation

In this section, the instructor explains how to understand API documentation and demonstrates how to use the book ordering API documentation.

What is API Documentation?

  • API documentation explains how to use an API and what's available.
  • Any API you want to use should have documentation that explains how to use it.

Using Book Ordering API Documentation

  • The instructor demonstrates how to find the book ordering API documentation and shows what endpoints are available.
  • Endpoints offer different kinds of responses, and we'll be exploring them throughout the course.

Sending a Request in Postman

In this section, the speaker demonstrates how to send a request in Postman and explains the different parts of an HTTP request message and response message.

Parts of an HTTP Request Message and Response Message

  • After sending a request in Postman, the status of the API is displayed in the lower part of the screen.
  • HTTPS stands for Hypertext Transfer Protocol Secure. Most APIs should be using HTTPS for secure connections.
  • The HTTP message that goes from Postman to the API is called a request, while what comes back from the API is called a response.
  • The upper part of the screen represents the request in Postman. It allows you to configure many things about the request, such as URL or address, method, headers, and body.
  • The response contains some properties such as status code, headers (like content type), and most importantly, response body which contains all information requested from server.

Saving Requests in Collections

In this section, we learn how to save requests in collections so they can be reused later.

Saving Requests in Collections

  • To save requests for reuse later on, we need to create collections. A collection is essentially a list of multiple requests typically connected to one API.
  • We can give each collection a name depending on use cases.
  • Once saved into collections we can find them in the collections tab and run them again.
  • We can replace addresses or configurations with variables that we can configure in a single place. This is useful in case something changes.

Saving and Editing Requests

In this section, the speaker explains how to save and edit requests in Postman.

Saving a Request

  • To save a request, click on the "Save" button in Postman.
  • The saved request will be added to the selected collection.
  • Hovering over a saved variable will display its value.

Editing Variables

  • To edit variables, hover over the collection name and select "Edit".
  • From the variables tab, you can change the base URL variable.
  • The initial value is shared with others while the current value is private to you.

Manually Adding Variables

  • If set variable option doesn't appear when selecting an address, manually add variables for any variables in Postman.
  • The initial value is not used when sending a request and will be shared with others.

Using APIs - List of Books Endpoint

In this section, the speaker demonstrates how to use APIs by exploring the list of books endpoint.

Accessing List of Books Endpoint

  • Open up a new tab in Postman and paste the address for the list of books endpoint.
  • Click on "Send" to see what happens.
  • A status 200 indicates that everything is fine and we have received a list of different books in JSON format.

Query Parameters

  • Query parameters are additional data that can be submitted with our request.
  • They are optional for this API.
  • We can add query parameters under "Query Params" in Postman.

Example:

  1. Select "parents".
  1. Add key-value pair "type:crime" to filter through all the books and only get the books that are crime books.
  1. The address will change as you type.

Query Parameters in Postman

In this section, the speaker explains how to use query parameters in Postman. They demonstrate how to add and remove query parameters, and explain the importance of reading API documentation.

Adding Query Parameters

  • To filter results using query parameters, select "fiction" instead of "crime" under the "type" parameter.
  • Multiple query parameter pairs can be sent with a request by separating them with an "&" symbol.
  • Copying and pasting the exact name of a query parameter from API documentation can help avoid spelling errors.

Using the Limit Parameter

  • The limit parameter is optional and limits the number of results returned by a request.
  • The limit value must be between 1 and 20. Values outside this range will result in a bad request error.
  • To use the limit parameter, add it as a key-value pair to your request URL (e.g. "?limit=2").

Path Variables in Postman

In this section, the speaker explains how to use path variables in Postman. They demonstrate how to specify values for path variables and explain their importance.

Using Path Variables

  • Path variables are used when making requests for specific resources that have unique identifiers (e.g. book IDs).
  • Path variables are specified in curly braces within the URL path (e.g. "/books/book_id").
  • To specify a value for a path variable, use the double curly brace syntax and include the variable name in your request URL (e.g. "/books/book_id").

Getting Detailed Information

  • The endpoint for getting detailed information about a single resource is different from the endpoint for getting a list of resources.
  • When making requests for detailed information, use the appropriate endpoint and specify the unique identifier as a path variable.

Understanding Path Variables

In this section, the speaker explains path variables and how they differ from query parameters.

Path Variables vs Query Parameters

  • Path variables are different from query parameters as they do not have a question mark and are part of the URL path.
  • The key for the path variable will not be sent in the request, only its value will be sent.
  • Path variables can have different values such as id1, id2, id4 etc., making them more flexible than query parameters.

Creating a Post Request with Authorization

In this section, the speaker explains how to create a post request with authorization.

Submitting an Order

  • To submit an order, we need to use the orders endpoint with a post request.
  • We can duplicate an existing request and change its path to create a new order request.
  • A post request requires us to supply a body which is currently missing in our order request.

Authentication for Private Endpoints

  • Private endpoints require authentication while public endpoints do not.
  • To authenticate ourselves, we need to register our API client and obtain an access token which acts like a temporary password that we can use with all our requests.

Registering API Client

  • We need to submit another post request to api-clients endpoint with JSON body containing necessary details to register our API client and obtain an access token.

Sending a JSON Request Body

In this section, the speaker explains how to send a JSON request body using Postman.

Selecting the POST Request Method and Adding a JSON Request Body

  • To submit a request body, select the POST request method.
  • Click on "Body" and select "raw" from the dropdown menu.
  • Select "JSON".
  • Copy and paste the example provided in the API documentation for the request body.

Validating JSON Before Submitting

  • Ensure that all values are enclosed in double quotes.
  • If there is an error with the JSON, something will appear in red. Fix any errors before submitting.

Checking Response Status Code

  • A status code of 201 indicates that everything was okay.
  • Any status code starting with 4 indicates that there was an issue with the submitted data.
  • A status code of 500 typically indicates a server issue or other problem.

Saving Access Token as Variable

In this section, the speaker explains how to save an access token as a variable in Postman.

Copying Access Token

  • Double-click on the access token to copy it.

Creating Variable for Access Token

  • Click on "Edit" and open variables.
  • Add a new variable called "access token".
  • Do not add your token to initial value if sharing collection with others.

Saving Current Value of Access Token

  • The current value is what is being used by Postman inside this installation.

Adding Authorization Header

In this section, the speaker explains how to add an authorization header when working with APIs.

Importance of Authorization Header

  • When working with APIs, you will not be provided with a form to add your username and password.
  • Authentication information must be sent with the request.
  • Typically, authentication information is added to the headers.

Using Authorization Helper in Postman

  • Click on "Authorization" tab in Postman.
  • Select "Bearer Token".
  • Add token using variable syntax (e.g. access token).

Auto-Generated Authorization Header

  • Postman auto-generates an authorization header called "authorization".
  • The value of this header must include the word "Bearer", followed by a space, and then the token.

Submitting an Order and Understanding JSON

In this section, the speaker discusses how to submit an order using an API and how to understand JSON.

Submitting an Order

  • To submit an order, we need to tell the API which book we want by submitting a request body in a JSON format.
  • The request body should include specific properties that are outlined in the API documentation.
  • It's important to ensure that the JSON we're sending is valid, or else the API won't be able to understand what we mean.
  • Postman can help identify invalid JSON, but it's still important to understand what JSON is and how it works.

Understanding JSON

  • JSON is essentially a key-value way of sending data.
  • Keys must be specified with quotes and separated from their values with colons.
  • Values can be strings, numbers, booleans, or nulls.
  • If we try to write something different than what is expected for valid JSON syntax (e.g. using single quotes instead of double quotes), it will not be considered valid.

Assignment on Submitting Orders and Identifying Books Out of Stock

In this section, the speaker gives an assignment on submitting orders and identifying books out of stock.

Assignment Details

  • The assignment involves creating a post request for submitting an order using valid JSON and identifying a book within a collection of books that has zero stock.
  • Once identified, attempt to order that book as well and see what happens.

Solution Walkthrough

  • To create a post request for submitting an order, follow the instructions outlined in the previous section on submitting orders.
  • To identify a book with zero stock within a collection of books:
  • Use filters provided by the API documentation to find all available books
  • Remove any filters to see all books
  • Look for a book with an "available" property set to false and check its stock level using the get single book endpoint.
  • Attempting to order a book with zero stock will result in a 404 not found error.

Importance of Using Varied Data When Testing APIs

In this section, the speaker emphasizes the importance of using varied data when testing APIs.

  • Reusing the same data over and over again can prevent us from identifying issues with the API.
  • It's important to use varied data when testing APIs to ensure that they work properly under different circumstances.

Using Postman's Random Variable

In this section, the speaker explains how to use Postman's random variable to generate a random customer name when sending requests.

Generating a Random Customer Name

  • To send requests with a random customer name, use Postman's random variable.
  • Remove the hardcoded customer name and enter two double curly braces followed by a dollar sign to access the list of available variables.
  • Type "random" and select "random full name" to generate a random full name for the customer.
  • Always enclose strings in double quotes to ensure valid JSON.

Using Postman Console for Debugging

In this section, the speaker explains how to use Postman console for debugging purposes.

Accessing Postman Console

  • Click on "console" at the bottom of the screen to open up Postman console.
  • Clear previous logs if necessary by clicking on "clear".
  • Send a request and expand it in console by clicking on it.
  • View request headers and body in console window.

Benefits of Using Postman Console

  • Use Postman console for debugging when something goes wrong or when you don't understand what's going on.
  • The postman console is particularly useful for debugging API calls.

What Not To Do With Postman

In this section, the speaker explains what not to do with Postman.

Limitations of Using Postman

  • Do not use postmate as a tool for dealing with user interaction such as forms or buttons.
  • It is not designed for performance testing or any kind of tests where you need to send many requests in a short time frame.
  • Although you can use it for security testing, it is not the primary focus of the tool.

Viewing a Single Order ID

In this section, the speaker explains how to view a single order ID.

Finding an Endpoint to View a Single Order ID

  • Check API documentation for an endpoint that allows you to view a single order ID.
  • Duplicate the previous request and change it from "post" to "get".
  • Use the order ID to find and view a specific order.

Benefits of Viewing a Single Order ID

  • Allows you to view individual orders instead of all orders at once.

Using API Endpoints in Postman

In this section, the speaker demonstrates how to use API endpoints in Postman. The speaker shows how to get an order, update an order, and delete an order using HTTP request methods.

Getting an Order

  • To get an individual order, use the endpoint "getting order" with a specific order ID.
  • Use the HTTP GET method to retrieve the information.
  • If you type in a value that doesn't exist, you will receive a 404 not found error.

Updating an Order

  • Use the endpoint "update an order" with the HTTP PATCH method to update existing orders.
  • You can only update specific properties depending on the API.
  • Use JSON format to send data through Postman.
  • After updating, use the GET method again to confirm changes.

Deleting an Order

  • Use the endpoint "delete an order" with the HTTP DELETE method to remove orders.
  • Confirm deletion by using GET method again.

Postman API Testing: Writing Tests

In this section, the instructor introduces the concept of automating testing using Postman. The goal is to write tests that will allow us to verify the API's status and response without manual intervention.

Introduction to Automated Testing

  • Manual testing can be time-consuming and prone to errors.
  • Automated testing allows us to test the API with just one command or click.
  • We want Postman to do the work for us by writing API tests.
  • We need to ensure that our tests will fail if something goes wrong.

Writing Tests in Postman

  • Instead of manually verifying responses, we can use Postman's "Tests" feature.
  • The "Tests" window allows us to write JavaScript code snippets that will execute when a response arrives.
  • We can use pre-written code snippets or write our own JavaScript code.
  • A simple test we can write is checking if the status code is 200.
  • We must ensure that our tests will also fail if there are any mistakes in our code.
  • We can also verify the response body, which is usually written in JSON format.

Parsing Response Data

  • To use response data inside JavaScript, we need to parse it first using JSON.parse().
  • Parsed data becomes an object that we can manipulate and use inside our tests.

Parsing JSON Response in JavaScript

In this section, we learn how to parse a JSON response into a JavaScript object and access its properties. We also learn how to use console.log to view the response and write tests using pm.test and pm.expect.

Parsing JSON Response

  • To parse a JSON response into a JavaScript object, assign the response to a variable in JavaScript.
  • Use console.log to view the contents of the variable in the Postman console.
  • Access properties of the object using dot notation or square brackets with a string parameter for property names with special characters.
  • Ensure that you can see what you're trying to test inside console.log.

Writing Tests Using pm.test and pm.expect

  • A test in Postman starts with pm.test.
  • The first parameter is the name of the test, while the second parameter is a callback function where assertions are written.
  • Use pm.expect followed by an assertion method like .eql or .to.deep.equal to compare values.
  • Use double quotes around strings when making assertions.
  • Write tests for all requests in your collection and ensure they fail if needed.

Assignment: Writing Status Code Tests

In this section, we are given an assignment to write status code tests for all requests in our collection. We are instructed on how to create these tests using pm.test and pm.expect.

Writing Status Code Tests

  • Write status code tests for all requests in your collection using pm.test.
  • The first parameter is the name of the test, while the second parameter is a callback function where assertions are written.
  • Use pm.expect followed by an assertion method like .to.equal or .to.be.oneOf to compare status codes.
  • Ensure that your tests fail if needed.

Using Postman for API Testing

In this video, the speaker demonstrates how to use Postman for API testing. The focus is on using variables to store data and make requests more efficient.

Storing Order IDs in Global Variables

  • To avoid copy-pasting order IDs between requests, global variables can be used.
  • Global variables are available across all collections in a workspace.
  • Clicking the "eye" icon next to a value allows you to define a global variable.
  • Use double curly braces around the variable name (e.g. order id) in subsequent requests.

Efficient Request Testing

  • Use collection variables or environment variables to store frequently-used values like base URLs or authentication tokens.
  • Test individual requests with simple tests that check for expected status codes.
  • Adapt tests as necessary when changes are made to the API being tested.

Conclusion

Postman is a powerful tool for API testing that can save time and effort by using variables and simple tests. By storing frequently-used values in global or environment variables, testers can streamline their workflow and focus on identifying issues with individual requests.

Postman Tutorial

In this tutorial, we learn how to use Postman to test APIs. We will cover how to create collections, add requests, and write tests.

Creating Collections

  • To create a new collection, click on the "New" button in the top left corner of the screen.
  • Give your collection a name and click "Create".
  • To add a request to your collection, click on the "Add Request" button.
  • Enter the request URL and select the HTTP method.

Writing Tests

  • To write tests for your requests, go to the "Tests" tab.
  • Write JavaScript code that validates the response from your API.
  • Use pm.test() function to write assertions for status codes and response body.

Dynamic Data

  • Hard-coded data makes our tests susceptible to changes. We need dynamic data instead.
  • Use variables in Postman to store dynamic data.
  • Use pm.sendRequest() function to send a request and get data dynamically.

Conclusion

  • Postman is a powerful tool for testing APIs. With its ability to create collections, write tests, and handle dynamic data, it can greatly simplify API testing.

Extracting Hidden Properties from API Responses

In this section, the speaker demonstrates how to extract hidden properties from API responses using Postman.

Setting a Global Variable

  • To extract hidden properties from an API response, set a global variable in Postman.
  • Use the "Set a Global Variable" code snippet in Postman to generate the necessary code.
  • Specify the name of the variable and its value (in this case, an object property).
  • After sending the request, check that the global variable has been properly set by clicking on the "i" icon.

Writing Tests for API Responses

  • Write tests for API responses to ensure that they meet certain criteria.
  • Use pm.test and pm.expect to write assertions for specific properties of an object returned by an API.
  • For example, use pm.expect(book.available).to.equal(true) to test whether a book is available.
  • Use conditional statements like if (book) to handle cases where no books are found.

Assignment: Testing Non-Fiction Books

  • Write an expectation that tests whether a book is non-fiction.
  • Duplicate the previous expectation and change it to test for non-fiction books specifically.

Disabling Type and Checking Current Stock

In this section, the speaker discusses disabling the type and changing it to fiction. They also talk about checking if the current stock is greater than zero.

Using Book ID in Get Single Book and Order Book

  • The assignment requires using the variable book id saved as a global variable in both get single book and order book requests.
  • Replace any hard-coded values with book id as a global variable.

Checking Current Stock

  • Parse the response by defining a variable called response and using pm.response.json.
  • Expect that response's current stock is above zero.
  • Use square brackets instead of dot notation when getting properties from an object with hyphens or dashes.

Test Automation with Collection Runner

In this section, the speaker introduces Postman's collection runner tool for executing an entire collection with just one click.

Running Collection with Collection Runner

  • Click on the runner button located at the bottom of the screen.
  • Drag and drop the collection into the runner.
  • Organize requests in order of execution.

Saving Responses and Fixing Order ID

In this section, the speaker discusses how to save responses and fix the order ID issue.

Saving Responses

  • It is important to save responses in case something goes wrong during execution.
  • Click on the "Run" button to execute the requests.

Fixing Order ID Issue

  • The "Get an Order" request has failed due to a manually hard-coded order ID.
  • To fix this issue, set a global variable named "order id" using pm.request.json.
  • Run the request again and inspect it to ensure that the updated order ID matches the response.
  • After fixing the order ID issue, all requests except for "Register API Client" are working properly.

Influencing Request Execution Order

In this section, the speaker discusses how to influence the order in which requests are executed.

Setting Next Request

  • Postman allows us to specify where postman should go with the next request by writing "postman.setNextRequest".
  • We can skip certain requests by specifying their names as strings after "setNextRequest".
  • Alternatively, we can move unwanted requests to the end of our collection and use "postman.setNextRequest(null)" to stop execution.

Automating API Testing with Postman

In this video, the speaker demonstrates how to automate API testing using Postman. They cover topics such as creating collections, writing tests, using variables and environments, running collections with the collection runner, and monitoring collections with Postman monitors. They also introduce Newman, a CLI tool that can be used to run Postman collections locally.

Creating Collections

  • To create a new collection in Postman, click on the "New" button in the top left corner of the app and select "Collection".
  • You can add requests to your collection by clicking on the "Add Request" button within your collection.
  • You can organize your requests into folders within your collection by clicking on the "Create Folder" button within your collection.
  • You can use variables in your requests by enclosing them in double curly braces (e.g. variable_name).

Writing Tests

  • To write tests for a request, click on the "Tests" tab within that request.
  • Tests are written in JavaScript and can be used to verify that an API is returning expected results.
  • You can use assertions like pm.expect() to check if certain conditions are true or false.

Using Variables and Environments

  • Variables allow you to store values that you want to reuse across multiple requests or tests.
  • Environments allow you to define sets of variables that are specific to different environments (e.g. development vs production).
  • You can switch between environments by clicking on the "Environment" dropdown in the top right corner of the app.

Running Collections with the Collection Runner

  • The Collection Runner allows you to run a collection multiple times with different sets of data.
  • You can define variables for your collection runs by clicking on the "Data" tab within the Collection Runner.
  • You can use conditions in your tests to control whether or not certain requests are executed.

Monitoring Collections with Postman Monitors

  • Postman Monitors allow you to schedule and run collections at specific intervals.
  • You can create a new monitor by clicking on the "Monitors" tab within your workspace and selecting "Create a Monitor".
  • Monitors run on Postman's infrastructure, so they don't require your computer or browser to be running.

Using Newman

  • Newman is a CLI tool that allows you to run Postman collections from the command line.
  • To install Newman, you need to have Node.js installed on your computer.
  • You can export a collection as a JSON file and then use Newman to run it locally.

Generating Public Links and Reports with Newman

In this section, the speaker demonstrates how to generate public links for Postman collections and how to use Newman to run collections from the terminal. The speaker also explains how to generate HTML reports using Newman.

Generating Public Links for Postman Collections

  • A public link can be generated for a Postman collection by clicking on "Share Collection" and then selecting "Get Public Link."
  • Another way to access a collection is through the Postman API using an API key.
  • When using environments in a collection, they must be exported and specified in the command when running the collection.

Running Collections with Newman

  • To run a collection from the terminal, navigate to the folder where it is saved and use the command "newman run [path/to/collection]."
  • Collections can also be run by specifying their public link in the newman run command.
  • Newman may fail if there are missing variables or tokens that have not been set properly.

Generating HTML Reports with Newman

  • The HTML Extra reporter is a popular report format that provides detailed information about requests and responses.
  • To install this reporter, use the command "npm install -g newman-reporter-html-extra."
  • When running a collection with Newman, specify "--reporters cli,html-extra" to generate an HTML Extra report.
  • The HTML Extra report provides an overview of all requests and responses sent during execution. It can help identify issues such as missing authorization tokens or unresolved variables.

The Big Picture of Automation with Newman

In this section, the speaker provides an overview of how Newman fits into the automation process for APIs.

  • The automation process for APIs typically involves a build pipeline, internal tests, deployment to a server, and API testing.
  • Newman is an important tool in the API testing stage as it allows for automated testing of collections from the command line.
  • There are many configurations available when using Newman and its reporters. It is important to become familiar with the documentation to fully utilize its capabilities.

API Testing with Postman

In this video, the instructor explains how to use Postman for API testing. The video covers topics such as manual testing, writing API tests, and automating test execution using Newman.

Manual Testing

  • Manually test an API by sending requests and examining responses in a tool like Postman.
  • Use the Postman console to view request and response details.
  • Use the Postman history tab to view previous requests and responses.

Writing API Tests

  • Write tests in JavaScript using the Chai Assertion Library.
  • Use variables, objects, and arrays in tests to make them more dynamic.
  • Write pre-request scripts to set up data or environment variables before running a request.
  • Write test scripts to validate response data or status codes.

Automating Test Execution with Newman

  • Install Newman globally using npm.
  • Run collections from the command line using Newman.
  • Specify environments and reporters when running collections with Newman.
  • Integrate Postman collections with CI/CD servers like GitLabCI, Jenkins, TeamCity, or CircleCI.

Conclusion

  • Recap of what was covered in the video.
  • Suggestions for further learning on topics like data-driven testing, schema validation, and OAuth2 authentication.