Home Web Development API Testing and Development with Postman - Second Edition

API Testing and Development with Postman - Second Edition

By Dave Westerveld
books-svg-icon Book
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This is an Early Access product. Chapters may lack final editing and while we strive for accuracy, the content is subject to updates during development. Learn more.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This is an Early Access product. Chapters may lack final editing and while we strive for accuracy, the content is subject to updates during development. Learn more.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    1 API Terminology and Types
About this book
Postman is an invaluable tool for exploration and testing of web APIs and helping testers and developers figure out how an API works. With Postman, you can create effective test automation for any APIs, and this guide will help you unleash its full potential. API Testing and Development with Postman is an invaluable resource for anyone who wants to create a good quality API, but isn't sure how to go about it. This guide will help you unleash the full potential of Postman’s test automation capabilities. A combination of theory coupled with real-world examples will help you learn how to use Postman to create well-designed, documented, and tested APIs. After you’ve familiarized yourself with the theory, you’ll move on to hands-on projects that will teach you how to add test automation to an existing API. You’ll also learn some of the new and powerful features that Postman has that can help you avoid introducing bugs. This second, fully updated edition features new chapters on workflow testing, creating and using mock servers, API security testing, and performance testing. The new and expanded information in this edition will help you future-proof your APIs. By the end of this book, you'll be able to use Postman to set up and run API tests for any API that you are working with.
Publication date:
31 May 2024
Publisher
Packt
ISBN
9781804617908

 

Join our book community on Discord

https://packt.link/vODyi

Qr code Description automatically generated

Learning something new can feel a little like falling over the side of a ship. Everything is moving and you can barely keep your head above water. You are just starting to feel like you understand how something works and then a new piece of knowledge comes out of nowhere and your whole world feels topsy turvy again. Having something solid to hold on to gives you the chance to look around and figure out where you are going. This can make all the difference in the world when learning something new.In this chapter, I want to give you that piece of land to stand on. As with almost any specialty, API testing and development has its own terminology. There are many terms that have specialized meanings when you are working with APIs. I will be using some of those terms throughout this book and I want to make sure that you and I share a common understanding of what they mean. This will allow me to more clearly communicate the concepts and skills in this book and will give you that piece of solid ground to stand on as you try to learn how to do effective API testing and development. As much as possible, I will use standard definitions for these terms, but language is a byproduct of humans and human interactions and so there is some degree of messiness that comes into play. Some terms do not have clearly agreed-on definitions. For those terms, I'll share how I intend to use and talk about them in this book. However, be aware that as you read or listen to things on the internet (or even just interact with teammates), you may come across others that use the terms in slightly different ways. Pay attention to how others are using a term and you will be able to communicate well. This book is not a dictionary, and so I don't intend to just write down a list of terms and their definitions. That would be boring and probably not all that instructive. Instead, I'll spend a bit of time on the theory of what an API is and how you test it. I will fit in some terminology explanations as we go. This chapter will cover the following main topics:

  • What is an API?
  • Types of API calls
  • Installing Postman
  • The structure of an API request
  • Considerations for API testing
  • Different types of APIs

By the end of this chapter, you will be able to use Postman to make API requests and have a good grasp of basic API terminology. You will also have the opportunity to work through an exercise that will help you cement what you are learning so that you can start to use these skills in your day-to-day work.

 

What is an API?

A 1969 NASA publication entitled Computer Program Abstracts (which can be found at the following link: https://tinyurl.com/y52x4aqy) contains a summary of a real-time display control program sold by IBM (only $310! Plus $36 if you want the documentation). This program is said to have been designed as an operator-application programming interface, in other words, an API.Application Programming Interfaces, or APIs, have been around for about as long as computer code has. Conceptually, it is just a way for two different pieces of code (or a human and some code) to interface with each other. A class that provides certain public methods that other code can call has an API. A script that accepts certain kinds of inputs has an API. A driver on your computer that requires programs to call it in a certain way has an API.However, as the internet grew, the term API narrowed in focus. Almost always now, when someone is talking about an API, they are talking about a web API. That is the context I will use in this book. A web API takes the concept of an interface between two things and applies it to the client/server relationship that the internet is built on. In a web API, a client is on one side of the interface and sends requests, while a server (or servers) is on the other side of the interface and responds to the request. Over time, the internet has changed and evolved, and web APIs have changed and evolved along with it. Many early web APIs were built for corporate use cases with strict rules in place as to how the two sides of the interface could interact with each other. The SOAP protocol was developed for this purpose. However, in the early 2000s, the web started to shift toward becoming a more consumer-based place. Some of the e-commerce sites, such as eBay and Amazon, started to publish APIs that were more public and flexible. This was followed by many of the social sites, including Twitter, Facebook and others. Many of these APIs were built using the REST protocol, which was more flexible and is built directly on the underlying protocols of the internet. The internet continued to change though, and as mobile applications and sites grew in popularity, so did the importance of APIs. Some companies faced challenges with the amount of data they wanted to transfer on mobile devices, and so Facebook created GraphQL. This query language helps to reduce the amount of data that gets transferred while introducing a slightly more rigid structure to the API. Each of the different API types work well in some scenarios, and I will explain more about what they are later in the chapter. However, before I get into the differences between them, I want to talk about some common terms that all web APIs share.

 

Types of API calls

Some calls to APIs can change things on the server, while others return data without changing anything. The terms safe and idempotent are used to descript the different ways that API calls can affect data. These terms might sound a bit intimidating so in order to better understand them let’s look at an illustration that uses Lego pieces.Imagine that there is a table with a couple of Lego pieces on it and I’m sitting by the table. I represent an API, while the Lego pieces represent a server. If you come along and want to interact with the Lego, you have to do so through me. In this illustration, the Lego pieces represent objects on a server, I represent an API and you represent a client. In picture form it looks kind of like this:

Figure 1.1 – Representation of a server and a client connect by an API

You are going to be the client in this imaginary relationship. This means you can ask me to do things with the Lego. You ask me to tell you what size the top Lego piece is. I reply that it is has a size of one. This is an example of an API request and response that is safe. A safe request is one that does not change anything on the server. By asking me for information about what is going on in the server, you have not changed anything on the server itself. There are other kinds of API calls that can happen though. Imagine that you gave me a size two brick and asked me to replace the top brick on the stack with the one you gave me. I do that, and in doing so I have changed the server state. The brick stack is now made up of a size three brick followed by two size two bricks, as shown in the following diagram:

Figure 1.2 – New server state

Since the server has changed, this is not a safe request. However, if you give me another size two brick and ask me to once again replace the top brick with the brick you just gave me, nothing will change on the server. The stack will still be made up of a size three brick followed by two size two bricks. This is an example of an idempotent call. API calls that return the same result no matter how many times you call them are known as idempotent.Let's imagine one more type of call. In this case, you give me a brick and ask me to add it to the top of the stack. I do that and so now we have a stack of four bricks. This is clearly not a safe call since the server has changed, but is it idempotent? The answer is no, but take a second to think about it and make sure you understand why this call would not be idempotent.If you are struggling to see why it is not idempotent, think of what happens if you repeat the same request again. You give me another brick and you ask me to add it to the top of the stack. If I do that a second time, is the brick stack still the same as it was after the first time you added it? No, of course not! It now has five bricks and every additional brick you give to me to add to the stack will change it. An idempotent call is one that only changes things the first time you execute it and does not make any changes on subsequent calls. Since this call changes something every time, it is not idempotent.Safety and idempotency are important concepts to grasp, especially when it comes to testing APIs. For example, if you are testing calls that are safe, you can run tests in parallel without needing to worry about them interfering with each other. But if you are testing calls that are not safe or idempotent, you may need to be a little more careful about what kinds of tests you run and when you run them.I want to talk about a few more terms and dig into the structure of API requests. However, it will be a lot easier to do that if we have something concrete to look at, so at this point let's take a brief pause to install Postman.

 

Installing Postman

Postman can be run on the web or as a desktop application. The functionality and design are similar between the web and desktop applications, but in this book, I will mostly use the desktop application and so I would recommend installing it. The app is available for Windows, Mac and Linux, and installing it is the same as pretty much any other program you’ve installed. However, I would highly recommend creating a Postman account if you don’t already have one. creating an account is totally free and it makes it a lot easier to manage and share your work. Everything in this book will work with the free features of Postman, however, some of the things that I will cover will assume that you have a Postman account so I would strongly recommend that you register for one.Go to https://postman.com and choose the Sign Up for Free option. Create an account and when asked how you want to use Postman, choose the Download Desktop App and then install it as you would any program on your computer. I will be using the Mac version of Postman, but other than the occasional screen shot looking a bit different, everything should be the same regardless of which platform you are running Postman on. If you already have a Postman account, but you don’t yet have the desktop app, you can download it directly from the Postman home page(https://postman.com).I will primarily use the desktop application in this book, but there are times when the web application is helpful. I would recommend that you set it up as well. During the sign-up process you can download the Desktop Agent. This agent allows the web version of Postman to get around some of the cross-origin restrictions that web browsers put on web requests. These restrictions are very important for security on the web, but when testing we often need to be able to work around them and this agent will allow you to do that. Once again, you can download and install this as you would any other program.

Starting Postman

Once you have Postman installed, open the application. The first time you open Postman, it will ask you to sign in. Once you've signed in, you will see the main screen with a bunch of different options for things that you can do with Postman. Don't worry about all these options. We will cover all of them (and more) as we go through this book. For now, just note that they are there and that you can do a lot of cool stuff with Postman. Maybe even get a little bit excited about how much you are going to learn as you go through this book!

Setting up a request in Postman

It's time to set up an API call so that we can dissect it and see how it all works. If the initial pop-up is still open, choose the HTTP Request building block. If it is not open, you can open it by going to the Home tab and in the Get started with Postman section choosing the Create New link.

Figure 1.3 – Create a new Postman Building Block

For this first example, I will use the Postman Echo API. This is an API Postman provides that can be used for doing some simple testing. In the field that says “Enter request URL” type in the following url: https://postman-echo.com/get. Click on the Send button to the right of the url field and you should see a response come back from the server. Don’t worry about the actual data of the response, for now just congratulate yourself for having sent your first request with Postman!

Saving a Request

Now that you have created a request, let’s look at how to save requests in Postman. Postman requires that requests be saved into something called Collections. Collections are a way to collect multiple requests that belong together. If you click on the Save button above and to the right of the request url, Postman will prompt you to create a collection to save the request in to. Click on the Create a collection button.Name the collection something like Postman Echo Requests and click Create. Now click the Save button on the dialog This will create the collection for you and save the request into that collection. Now that you have saved a request, let’s start digging into the basic structure of an API request.

 

The structure of an API request

The request tab in Postman provides a lot of information about the various pieces that make up an API request. Each of these pieces plays an important part in sending and receiving data with an API, and so I will walk you through each one in turn. Some parts of an API request are optional depending on what kind of request it is and what you are trying to do with it, but there are two pieces that are required for every API request. Every API request needs an endpoint and an action.

API endpoints

Every web-based API request must specify an endpoint. In the Postman requests tab, you are prompted to enter the request URL. Postman is asking you to put in a URL because an API endpoint is just a URL. We use the term URL so much that we can sometimes forget what it stands for. URL is an acronym for Uniform Resource Locator. The endpoint of an API call specifies the resource, or the "R" of the URL. In other words, an API endpoint is the uniform locator for a particular resource that you want to interact with on the server. URLs help you to locate resources on a server, and so they are used as the endpoints in an API call.In order to understand this, let’s set up a concreate example. First create a second collection. Click on the New button above the navigation panel and choose Collection on the popup. Name the collection something like Github API Requests. If you expand the collection, you will see a prompt to Add a request. Click on that link to add a new request.

Figure 1.4 Add a Request to a Collection

Name the request Get Repos and fill in the request URL field with the following URL: https://api.github.com/users/djwester/repos. This endpoint will give you information about my public repositories on GitHub. If you have a GitHub account of your own, you can put in your username in the part of the URL where it says djwester and get back data for your own repositories.You will often see an API endpoint specified without the base part of this API. So, for example, if you look at the GitHub API documentation, it will report the endpoint for this as /users/:username/repos. All the GitHub API calls start with the same base URL (in other words, https://api.github.com), and so this part of the endpoint is often left out when talking about an endpoint. If you see API endpoints listed that start with a / instead of with http or www, just remember that you need to go and find the base API URL for the endpoint in order to call it.

API actions

Every API call needs to specify a resource that we are working with. This is the endpoint, but there is a second thing that every API call needs. An API needs to do something with the specified resource. We specify what we want an API to do with API actions. These actions are sometimes called verbs, and they tell the API call what we expect it to do with the resource that we have given it. For some resources, only certain actions are valid, while for others there can be multiple different valid API actions.In Postman, you can select the desired action using the drop-down menu beside the textbox where you entered the URL. By default, Postman sets the action to GET, but if you click on the dropdown, you can see that there are many other actions available for API calls. Some of these actions are specialized for particular applications, and so you won't run into them very often. In this book, I will only use GET, POST, PUT, and DELETE. Many APIs also use PATCH, OPTIONS, and HEAD, but using these is very similar to using the four that I will use, and so you will be able to easily pick up on how to use them if you run into them. The rest of the actions in this list are not often used and you will probably not encounter them much in the applications that you test and create.The four actions (GET, POST, PUT, and DELETE) are sometimes summarized with the acronym CRUD. This stands for Create, Read, Update, and Delete. In an API, the POST action is used to create new objects, the GET action is used to read information about objects, the PUT action is used to modify existing objects, and (surprise, surprise) the DELETE action is used to delete objects. In practice, having an API that supports all aspects of CRUD gives you the flexibility to do almost anything you might need to, which is why these four actions are the most common ones you will see.API actions and endpoints are required for web APIs, but there are several other important pieces to API requests that we will consider.

API parameters

API parameters are used to create structure and order in an API. They organize similar things together. For example, in the API call we are looking at, we are getting the repositories for a particular user in GitHub. There are many users in GitHub, and we can use the same API endpoint to get the repository list for any of them by merely changing the username in the endpoint. That part of the endpoint where it accepts different usernames is a parameter.

Request parameters

The username parameter in the GitHub repositories API endpoint is known as a request parameter. You can think of a request parameter as a replace string in the API endpoint. They are very common in web APIs. You will see them represented in different ways in the documentation of different APIs. For example, the GitHub documentation uses a colon in front of the request parameter to indicate that it is a request parameter and not just another part of the endpoint. You will see endpoints specified like this in the GitHub documentation: /users/:username/repos.In other APIs you will see request parameters enclosed in curly braces instead. In that case, the endpoint would look like /users/{{username}}/repos. Whatever the format used, the point of request parameters is to get particular information about different objects that are all the same type. We have already seen how you can do that with this endpoint by replacing my username with your username (or any other GitHub user's name).

Query parameters

There is another kind of parameter that you can have in an API endpoint. This kind of parameter is known as a query parameter and it is a little bit trickier to deal with. A query parameter often acts like a kind of filter or additional action that you can apply to an endpoint. They are represented by a question mark in the API endpoint and are specified with a key that is the item you are querying for, and a value, which is what you want the query to return.That's all very abstract, so let's look at it with the GitHub request we have open. This endpoint supports a couple of different query parameters. One of them is the type parameter. In order to add parameters to an API endpoint in Postman, make sure you have the Params tab selected and then put the name of the query parameter into the Key field and the value into the Value field. In this case, we will use the type parameter, so enter that word into the Key field.For this endpoint, the type parameter allows us to filter based on whether you are the owner of a repository or just a member. By default, the endpoint will return only those repositories that you are the owner of, but if I want to see all the repositories that I am a member of, I can put member in the Value field for this. At this point, the request should look something like this:

Figure 1.5 – Query parameter type in an API call

You can see that when you specify query parameters in the params tab Postman automatically adds them to the request URL. If I send this request, I get back all the repositories that I am a member of, as opposed to the ones that I own. Parameters are a powerful API paradigm, but there are still a few more fundamental pieces of the API structure that I haven't talked about yet. The next thing we will look at are API headers.

API headers

Every API request needs to include some headers. Headers include some of the background information that is often not that important to human users, but they help the server have some information about the client that is sending the request. Sometimes we will need to modify or add certain headers in order to get an API to do what we want, but often we can just let the tool that we are using send the default headers that it needs to send without worrying about it.In Postman, you can see what headers will be sent with your request by using the Headers tab. You can also modify the headers and add additional ones here as needed. I will get into more details on how headers work and how to use them in future chapters, so for now, you don't need to worry about them too much. The point of mentioning them here is just to make sure you know the terminology. Let's turn our attention instead to the body of an API request.

API body

If you want to create or modify resources with an API, you will need to give the server some information about what kind of properties you want the resource to have. This kind of information is usually specified in the body of a request.The request body can take on many forms. If you click on the Body tab in the Postman request, you can see some of the different kinds of data that you can send. You can send from-data, encoded form data, raw data, binary data, and even GraphQL data. As you can imagine, there are a lot of details that go into sending data in the body of a request. Most of the time, GET requests do not require you to specify a body. Other types of requests, such as POST and PUT, which do require you to specify a body, often require some form of authorization since they allow you to modify data. We will learn more about authorization in Chapter 5, Understanding Authorization Options. Once you can authorize requests, there will be a lot more examples of the kinds of things you might want to specify in the body of an API request.

API response

So far, we have spent a lot of time talking about the various pieces that make up an API request, but there is one very important thing that we have been kind of ignoring. An API is a two-way street. It sends data to the server in the request, but then the server processes that request and sends back a response.The default view that Postman uses displays the response at the bottom of the request page. You can also modify the view to see the request and the response in side-by-side panels. You can change to this view if you so wish by clicking on the Two pane view icon at the bottom of the application, as shown in the following screenshot:

Figure 1.6 – Switching views

There are a few different aspects to the response. The most obvious one is the body of the response. This is usually where most of the information that you are looking for will be included. In the GitHub repositories requests that you have made, the lists of repositories will show up in the body of the response, and Postman will display them in that tab.An API response can also include a few other things such as cookies and headers. These kinds of things can be very important hints as to what is going on when testing or creating APIs, and I will talk about them more as we go through the bookWe have covered a lot of ground when it comes to how APIs request work. We have seen how an API request can have a lot of different pieces to it. These simple pieces all come together to create a powerful tool. You now have a grasp of the basic pieces that make up an API call and how to use them in Postman. It's almost time to talk about how to use this to test APIs, but before we get into that, I want to pause for a minute so that you can put into practice all this theory I've just gone over.

Learning by doing – making API calls

Books are a great way to grow and learn. You are reading this book, so I don't think I need to convince you of that! However, reading a book (or even three or four books) on a topic does not mean you understand that topic. There is theory and there is practice. There is knowing something that you've read and knowing something that you've done. These are two very different things, and if all you do is read about a topic, you will feel like you know that topic, but that will be more of a feeling than a reality. This book is a hands-on guide, and my purpose in writing this is to help you improve your skills around API testing and to give you a deep knowledge of how Postman can help you understand API quality.If you want that to be a reality and you don't just want this book to be another piece of theoretical knowledge bouncing around inside your head, you need to put into practice the things that you are learning. I know it's hard when you are reading a book. I personally find it difficult to interrupt the flow of a book that I am reading in order to do exercises. I get it. It feels like you are slowing down your learning. This isn't a book on the theory of how we learn, but please believe me when I say that you will learn a lot more if you pause along the way and work through practical examples related to what you have just been learning. I will include those throughout this book and encourage you to work through them. As with any learning project, you will get out of it what you put into it. Take that time to do the exercises.In order to help you with getting some hands-on experience, I have created some simple API applications that you can interact with. Keep in mind that these applications are just “toy” applications, meaning that they might do some things more simply than a “real” API. However, I hope they will be helpful for you as you are learning the topics in this book.

Setting up the Test Applications

We will get into some of the exercises that I have designed in a bit, but first I want to go through how to set them up. You can find the source code for them on GitHub (https://github.com/djwester/api-testing-lego). I have also included instructions there on how to set them up locally. If you want, you can run them locally. However, if you don’t want to go through the bother of setting them up locally you can also test against the hosted versions of them as well. Once again, the instructions for how to do that and what url to go to are on the GitHub page.

 

Considerations for API testing

This is a book about how to use Postman to make better APIs. Part of making a better API is testing it. There is a lot to API testing, and I will walk you through many aspects of it as we go through this book, but now that you know some of the basics of how an API request works, what are some of the things to consider when you test an API?

Beginning with exploration

I can still clearly remember the first time I saw a modern web API in action. The company I was working at was building a centralized reporting platform for all the automated tests and I was assigned to help test the reporting platform. One of the key aspects of this platform was the ability to read and manipulate data through a web API. As I started testing this system, I quickly realized how powerful this paradigm was.Another part of my job at that time was to work with a custom-built test automation system. This system was quite different from the more standard test automation framework that many others in the company were using. However, the fact that the new reporting platform had an API meant that my custom test automation system could put data into this reporting platform, even though it worked very differently to the other test automation systems. The test reporting application did not need to know anything about how my system, or any other one, worked. This was a major paradigm shift for me and was probably instrumental in leading me down the path to where I am writing this book. However, something else I noticed as I tested this was that there were flaws and shortcomings in the API.It can be tempting to think that all API testing needs to be done programmatically, but I would argue that the place to start is with exploration. When I tested the API for that test reporting platform, I barely knew how to use an API, let alone how to automate tests for it, and yet I found many issues that we were able to correct. If you want to improve the quality of an API, you need to understand what it does and how it works. You need to explore it.But how do you do that?Thankfully, Postman is one of the best tools out there for exploring APIs. With Postman, you can easily try out many different endpoints and queries and you can get instant feedback on what is going on in the API. Postman makes it easy to play around with an API and to go from one place to another. Exploring involves following the clues that are right in front of you. As you get results back from a request, you want to think of questions that those results bring to mind and try to answer them with further calls. This is all straightforward with Postman. To Illustrate, I will walk you through a case study of a short exploratory session using Postman.For this session, I will use the https://swapi.dev/ API. This is a fun little API that exposes data about the Star Wars movies. Don't worry if you aren't into Star Wars. No specialized knowledge is needed!

Exploratory testing case study

Let's try this out. First, create a new collection called Star Wars API and add a request to it called Get People. Put https://swapi.dev/api/people/1/ into the URL field and send that request. You should get back a response with some data for the character Luke Skywalker:

Figure 1.7 – Response for the Star Wars API request

In the response, there are links to other parts of the API. A response that includes links to other relevant resources is known as a Hypermedia API. The first link in the films list will give us information about the film with ID 1. Since we are exploring, let's go ahead and look at that link and see what it does. You can just click on it and Postman will open a new requests tab with it already loaded. At this point, you know what to do: just click on Send and Postman will give you data about that first film. Under the characters in that film, you can see that there are several different characters, including, of course, a link to /people/1.Seeing this triggers a thought that there might be more things to check in the /people API, so let's go back and explore that part of the API a bit more. Click on the Get People tab to go back to that request and change the URL to remove the /1 from the end of it. You can now click Send to send a request to the endpoint, https://swapi.dev/api/people. This response gives back a list of the different people in the database. You can see at the top of the response that it says there is a count of 82.We are in exploration mode, so we ask the question, "I wonder what would happen if I tried to request person number 83?" This API response seems to indicate that there are only 82 people, so perhaps something will go wrong if we try to get a person that is past the end of this dataset. In order to check this, add /83 to the end of the URL and click Send again. Interestingly (if the API hasn't changed since I wrote this), we get back data for a Star Wars character. It seems like either the count is wrong, or perhaps a character has been removed somewhere along the way. Probably we have just stumbled across a bug!Whatever the case may be, this illustrates just how powerful a little bit of exploration can be. We will get to some powerful ways to use Postman for test automation later in this book, but don't rush right past the obvious. API testing is testing. When we are testing, we are trying to find out new information or problems that we might have missed. If we rush straight to test automation, we might miss some important things. Take the time to explore and understand APIs early in the process.Exploration is a key part of any testing, but it takes more than just trying things out in an application. Good testing also requires the ability to connect the work you are doing to business value.

Looking for business problems

When considering API testing and design, it is important to consider the business problem that the API is solving. An API does not exist in a vacuum. It is there to help the company meet business needs. Understanding what those needs are will help to guide the testing approaches and strategies that you take. For example, if an API is only going to be used by internal consumers, the kinds of things that it needs to do and support are very different to those needed if it is going to be a public API that external clients can access.When testing an API, look for business problems. If you can find problems that prevent the API from doing what the business needs it to do, you will be finding valuable problems and enhancing the quality of the application. Not all bugs are created equal.

Trying weird things

Not every user of an API is going to use it in the way that those who wrote the API thought they would. We are all limited by our own perspectives on life, and it is hard to get into someone else's mind and see things through their perspective. We can't know every possible thing that users of our system will do, but there are strategies that can help you get better at seeing things in a different light. Try doing some things that are just weird or strange. Try different inputs and see what happens. Mess around with things that seem like they shouldn't be messed with. Do things that seem weird to you. Often, when you do this, nothing will happen, but occasionally it will trigger something interesting that you might never have thought of otherwise.Testing does not need to be mindless repetition of the same test cases. Use your imagination. Try strange and interesting things. See what you can learn. The whole point of this book is for you to learn how to use a new tool. The fact that you have picked up this book shows that you are interested in learning. Take that learning attitude into your testing. Try something weird and see what happens.There is obviously a lot more to testing than just these few considerations that I have gone over here. However, these are some important foundational principles for testing. I will cover a lot of different ways to use Postman for testing in this book, but most of the things that I talk about will be examples of how to put these strategies into practice. Before moving on to more details on using Postman though, I want to give you a brief survey of some of the different types of APIs that you might encounter.

 

Different types of APIs

There are several types of APIs commonly used on the internet. Before you dive too deep into the details of using Postman, it is worth knowing a bit about the different kinds of APIs and how to recognize and test them. In the following sections, I will provide brief explanations of the three most common types of APIs that you will see on the internet.

REST APIs

We'll start with what is probably the most common type of API you'll come across on the modern web, the RESTful API. REST stands for Representational State Transfer, and refers to an architectural style that guides how in terms of how you should create APIs. I won't go into the details of the properties that a RESTful API should have (you can look them up on Wikipedia if you want, at https://en.wikipedia.org/wiki/Representational_state_transfer), but there are a few clues that can let you know that you are probably testing a RESTful API.Since RESTful APIs are based on a set of guidelines, they do not all look the same. There is no official standard that defines the exact specifications that a response must conform to. This means that many APIs that are considered to be RESTful do not strictly follow all the REST guidelines. REST in general has more flexibility than a standards-based protocol such as SOAP (covered in the next section), but this means that there can be a lot of diversity in the way REST APIs are defined and used.So how do you know whether the API that you are looking at is RESTful?Well, in the first place, what kind of requests are typically defined? Most REST APIs have GET, POST, PUT, and DELETE calls, with perhaps a few others. Depending on the needs of the API, it may not use all these actions, but those are the common ones that you will be likely to see if the API you are looking at is RESTful.Another clue is in the types of requests or responses that are allowed by the API. Often, REST APIs will use JSON data in their responses (although they could use text or even XML). Generally speaking, if the data in the responses and requests of the API is not XML, there is a good chance you are dealing with a REST-based API of some sort. There are many examples of REST APIs on the web and, in fact, all the APIs that we have looked at so far in this book have all been RESTful.

SOAP APIs

Before REST, there was SOAP. SOAP stands for Simple Object Access Protocol. SOAP has been around since long before Roy Fielding came up with the concept of REST APIs. It is not as widely used on the web now (especially for smaller applications), but for many years it was the default way to make APIs and so there are still many SOAP APIs around.SOAP is an actual protocol with a W3C standards definition. This means that its usage is much more strictly defined than REST, which is an architectural guideline as opposed to a strictly defined protocol.If you want a little light reading, check out the w3 primer on the SOAP protocol (https://www.w3.org/TR/soap12-part0/). It claims to be a "non-normative document intended to provide an easily understandable tutorial on the features of SOAP Version 1.2”.I'll be honest, I'm not sure how well it delivers on the "easily understandable tutorial" part of that statement, but looking at some of the examples in there may help you understand why REST APIs have become so popular. SOAP APIs require a highly structured XML message to be sent with the request. Being built in XML, these requests are not that easy to read for humans and require a lot of complexity to build up. There are, of course, many tools (an example is SoapUI) that can help with this, but in general, SOAP APIs tend to be a bit more complex to get started with. You need to know more information (such as the envelope structure) in order to get started.But how do you know whether the API you are looking at is a SOAP API?The most important rule of thumb here is: does it require you to specify structured XML in order to work? If it does, it's a SOAP API. Since these kinds of APIs are required to follow the W3C specification, they must use XML, and they must specify things such as env:Envelope nodes inside the XML. If the API you are looking at requires XML to be specified, and that XML includes the Envelope node, you are almost certainly dealing with a SOAP API.

SOAP API example

Let's look at an example of what it would look like to call a SOAP API. This is a little bit harder than just sending a GET request to an endpoint, but Postman can still help us out with this. For this example, I will use the country info service to get a list of continents by name. The base page for that service is here: http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso. In order to call this API in Postman, we will need to set up a few things. You will, of course, need to create a request in Postman. In this case though, instead of having the request method as a GET request, you will need to set the request method to POST and then put in the URL specified above. SOAP requests are usually sent with the POST method rather than the GET method because they have to send XML data in the body of the request. You usually don’t send body data in a GET request, and so most SOAP services require the requests to be sent using the POST protocol.Don't click Send yet though. Since this is a SOAP API, we need to send some XML information as well. We want to get the list of continents by name, so if you go to the CountryInfoServices web page, you can click on that first link in the list, which will show you the XML definitions for that operation. Use the SOAP 1.2 example on that page and copy the XML for it.In Postman, you will need to set the input body type to raw and choose XML from the dropdown and then paste in the Envelope data that you copied from the documentation page. It should look something like this:

Figure 1.8 – SOAP API information

For this particular API, we also need to modify the Content-Type header. Go to the Headers tab and click on the button labeled hidden. You will see that Postman has automatically added a Content-Type header with a value of application/xml. However, this API needs the content type set to application/soap+xml. We can’t directly modify the automatically created but we can add one that replace this one. At the bottom of the list type Content-Type into the Key field and set the value to application/soap+xml. Postman will automatically put a strike through in the autogenerated headers, showing that it won’t use it and will instead use the one you specified. To be extra sure you can deselect it from the list as well.

Figure 1.9 – Content-Type header set to application/soap+xml

Now you are finally ready to click on Send. You should get back a list of the continents, but as you can see, there is a lot more complexity to calling SOAP APIs. REST APIs can, of course, have complex bodies specified as well, but the requirement to do this in XML and the existence of the Envelope node in this indicates that this API is indeed a SOAP API.

GraphQL APIs

SOAP came before REST and, in many ways, REST was designed to deal with some of the shortcomings of SOAP. Of course, in software we are never done making things better, and so we now have a type of API known as GraphQL. GraphQL is a query language that was designed to deal with some of the situations where REST APIs have shortcomings. RESTful APIs don't know what specific information you might be looking for, and so when you call a REST API endpoint, it gives back all the information it has. This can mean that we are sending extra information that you don't need, or it can mean that we aren't sending all the information you need and that you must call multiple endpoints to get what you want. Either of these cases can slow things down, and for big applications with many users, that can become problematic. GraphQL was designed by Facebook to deal with these issues.GraphQL is a query language for APIs, and so it requires you to specify in a query what you are looking for. With REST APIs, you will usually only need to know what the different endpoints are in order to find the information you are looking for, but with a GraphQL API, a single endpoint will contain most or all of the information you need, and you will use queries to filter down that information to only the bits that you are interested in. This means that with GraphQL APIs, you will need to know the schema or structure of the data so that you know how to properly query it, instead of needing to know what all the endpoints are.How do you know whether the API you are looking at is a GraphQL API?Well, if the documentation is telling you about what kinds of queries you need to write, you are almost certainly looking at a GraphQL API. In some ways, a GraphQL API is similar to a SOAP API in that you need to tell the service some information about what you are interested in. However, a SOAP API will always use XML and follow a strict definition in the calls, whereas GraphQL APIs will usually be a bit simpler and are not defined in XML. Also, with GraphQL, the way the schema is defined can vary from one API to another as it does not need to follow a strictly set standard.

GraphQL API example

Let's look at a real-life example of calling a GraphQL API to understand it a bit better. This example will use a version of the countries API that you can find hosted at https://countries.trevorblades.com/. You can find information about the schema for it on GitHub: https://github.com/trevorblades/countries. Now, you could just create queries in the playground provided, but for this example, let's look at setting it up in Postman.Similar to calling a SOAP API, we will need to specify the service we want and do a POST request rather than a GET request. GraphQL queries can be done with GET, but it much easier to specify the query in the body of a POST request, so most GraphQL API calls are sent with the POST method. You will need to choose the GraphQL option on the Body tab and put in the query that you want:

Figure 1.10 – GraphQL query

As you can see, in this example, I have requested the name and languages of Canada. Once I have specified this information, I can click Send and I get back some JSON with the country name and a list of the official languages. If I wanted additional information (say the name of the capital city), I could just modify the query to include a request for that information and send it off again using the same endpoint, and I would get back the new set of information that I requested.At this point, I have obviously only been able to give a very quick introduction to each of these types of APIs. If you are working with a GraphQL or SOAP API, you may need to spend a bit of time at this point making sure you understand a little more about how they work before proceeding on with this book. Most of the examples through the rest of this book will use RESTful APIs. The concepts of API testing will largely stay the same though, regardless of the type of API testing that you need to do. You should be able to take the things that you will learn in this book and put them to use regardless of the type of API you are working with in your day job.

 

Summary

Let's pause for a minute to consider everything we have gone over in this chapter. You've installed Postman and already made several API requests. You have learned how API requests work and how to call them. I explained some basic testing considerations and gave you strategies that you can start to use right now in your day-to-day work. You also got to make calls to GraphQL, SOAP, and REST APIs and learned a ton of API terminology.You now have some firm ground that you can stand on as we proceed through the rest of this book. I will take you deep into a lot of API testing and design topics and help you get the most out of Postman, but in order to get the most out of it and not feel frustrated, it would be good to make sure you understand the topics covered in this chapter.Take a minute to ask yourself the following questions:

  • Would I feel comfortable reading an article on API testing? Could I follow along with the terminology used?
  • What are some basic strategies and approaches that I can use in API testing?
  • If I was given an API endpoint, could I send a request to it in Postman? What things would I need to do to send that request?
  • If I was given some API documentation, could I figure out what kind of API it was and send requests to it?

If you can answer these questions, you certainly have the grounding that you need for moving on in this book. If you are not totally sure about some of them, you might want to review some of the relevant sections in this chapter and make sure you have that solid ground under your feet.You've learned a lot already! In the next chapter, we will dive into some of the principles of API design and look at how to use Postman to help put those principles into practice when creating an API.

About the Author
  • Dave Westerveld

    Dave Westerveld is test developer with many years of testing experience. He has been involved in the testing of many different projects ranging from well-established products to helping with the early stages of major new initiatives. He excels at solving automation problems in a team environment and has been involved in traditional automation initiatives at various stages. Dave has also helped to improve product quality through the creative use of automation tools and by helping build out automation frameworks. He has a desire to see teams efficiently producing high-value software and is enthusiastic about understanding the way that automation tools can be used to help with this goal. Currently, Dave works as a test developer at D2L, owner of the worlds first integrated learning platform. In this role, he has had the opportunity to learn a lot about services-based architecture and how to test them in the real world. As an employee at an educational company, Dave has a passion for sharing what he has learned with others. He is also passionate about the importance of producing good quality software and so is excited to be able to author courses that allow him to share some of his testing knowledge. He blogs at offbeattesting.

    Browse publications by this author
API Testing and Development with Postman - Second Edition
Unlock this book and the full library FREE for 7 days
Start now