loading...

Beginner's guide to writing API tests

lisahjung profile image Lisa ・13 min read

This is your moment.

You have put your blood, sweat, and tears into creating an API bursting with sexy data.

You fire up the front end of your app and click the button, eagerly waiting for API data to display on your browser.

...Why isn't anything showing up on your screen?!

alt giphy

One of the grave mistakes you can make as a beginner is not testing your API throughout development. An easy to fix bug could become a nightmare when it is hidden in a massive API.

Do your future self a favor by testing your API every step of the way. What is awesome is that you do not even need to write front end code to test it.

You can use Postman!

What is Postman?

Postman is a collaboration platform for API development. It has a free plan where you can design, develop, and test your API. You can also use it to explore third party APIs you want to incorporate into your app.

Objectives

During this tutorial, I will be using Trello REST API and Postman to show you how you can write API tests.

By the end of this blog, you will be able to:

  1. create a board and a list in Trello by sending post requests from Postman
  2. write API tests in Postman to ensure that API is functioning properly

Additional Resources

For those of you who are just getting your feet wet at creating an API or using Postman, I have written two blogs that explain these concepts more in depth. Check them out here:

  1. Beginner's guide to creating an API from scratch using Rails
  2. Beginner's guide to strong params and validations

I found Valentin Despa's Udemy course on Postman to be super helpful. This blog is based on what I have learned from this course.

Let's get started!

Prerequisite Download & Account Signup:

  1. Download Postman

  2. Sign up for a free Trello account here and log in.

Trello is another tool I use often as I love visually organizing my to do lists in categorized boards!

In order for you to access the Trello API, you will need an API key and a token. Click on this link. You will see the API key pulled up for you as shown below.

Alt Text

Save the key somewhere safe. Then, click on generate a Token link highlighted with red arrow.

Give Trello access to your account by clicking on Allow button at the bottom of the page. Save your token somewhere safe as we will be using both API key and token to test Trello API.

Alt Text

All right, now that we have set up all the tools we need, let's quickly go over the layout of Postman and Trello board.

Layout

Postman Layout

Alt Text

Postman workspace has a browser like interface as shown above. I have highlighted the features we will be using with colorful arrows.

Let's go over these one by one.

  1. HTTP method(red arrow): If you click on downward arrow, you will see multiple HTTP methods we can use to send requests to the API. For the purpose of this tutorial, we will be using HTTP method POST(create).

  2. URL bar(orange arrow): This is where we will enter the request URL to the Trello API we are testing.

  3. Send button(yellow arrow): Use this button will send our request to the API.

  4. Query params(green box): This is where we will be entering query parameters. Query parameters are optional key-value pairs that appear after the question mark in the URL(definition from rapid api). You can include additional info here when you are calling the resource. We will cover how we will be using query params shortly!

  5. Tests(blue arrow): Last but not least, tests is a tab where we will be writing API tests.

Trello Board Layout

Alt Text

Image above is a screenshot of my personal Travel Vision Board I have created with Trello. I LOVE going on adventures and this Trello board helps me visualize and check destinations off my list.

My travel vision board has three lists:

  1. Ooh wanna go there? This list contains destination cards of all the places I dream of visiting.
  2. Pack your bags! This list contains destination cards of places I am going to in the near future.
  3. Another great adventure - check! This list contains destination cards of places I have visited.

Now that we know the layout of the tools we will be using, let's delve into Trello API documentation

This documentation will help us figure out how we can send requests to Trello API from Postman. We will use this info to create a board and a list in Trello.

Writing API Tests

Task 1: Create a Trello Board by sending a post request to Trello API

Step 1: Pull up the Trello API documentation
This document has all the info we need to work with the API.

Step 2: Gather information on how to create a board on Trello
On the left side, there are variety of topics you can choose from. We are creating a board so expand the Boards topic then click on Create a Board(red box) option.

Alt Text

Info regarding creating a board should show up to the right(green box).

Pay attention to the region highlighted with green box above.

To create a board, it specifies that:

  1. we need to make a POST request
  2. our query parameters must include an API key, a token, and name of the board.

Scroll down until you see the example section. It will give you the url where you can make this post request.

Alt Text

Sweet. We now have all the info we need to create a board so let's open up Postman.

Step 3: Include all the necessary info in Postman to send the POST request to Trello API

Alt Text
Refer to the numbered arrows that correspond with the following directions.

  1. Change HTTP method to POST
  2. Copy and paste the url from Trello documentation in the url bar. The url from the most current documentation as of 8/14/2020 should the following:
    https://api.trello.com/1/boards/?key=0471642aefef5fa1fa76530ce1ba4c85&token=9eb76d9a9d02b8dd40c2f3e5df18556c831d4d1fadbe2c45f8310e6c93b5c548&name={name}

  3. Update query params with your own API key, token, and name of the board.

Remember that query params are specified in the request url after a ? and it allows you to send additional info to the API. If you look at the url, you will see that there are query parameters called key, token, and name(of the board).

If you try to send a request using the url from the API, it will not work as you will need to add your own API key and token to gain access.

Locate Query Params section highlighted in orange. There are two columns: key and value.

Alt Text

In the key column, write key, token, name as shown in the image.

In the value column, copy and paste the API key and token you have saved previously in the appropriate row.

For name key, enter the value as Travel Vision Board.

When you complete these fields, look at your url bar. You will see that the query params in your url have been updated with the info you have entered in query params key value table.

Step 4: Click send to submit the request to Trello API

Step 5: Assess the response you have received from Trello API in the body section(pink box).
Alt Text
You will see that an object with info about the created board has been returned to you. We have three clues that the board has been successfully created:

Clue #1 In the object returned, id has been assigned to this board. If the board has not been created successfully, the id returned would be null.

Clue #2 In the status section(baby blue box), we have received a status of 200 OK, meaning that board has been successfully created.

Clue #3 When you log into your Trello Account, you will see that Travel Vision Board has been successfully created in your account.

What we have just done is alternative ways to check if the API is working correctly. You can test the API with greater scrutiny by writing tests in Postman. We will go over this in Task 2!

Task 2: Create a list within the board by sending a post request

This task is very similar to creating a board.

Step 1: Pull up the Trello API documentation and gather information on how to create a list within a board.

Scroll down to Lists and select Create a New List.

Alt Text

Info regarding creating a list should show up to the right(green box).

Pay attention to the region highlighted with green box here.

To create a list, it specifies that:

  1. we need to make a POST request
  2. our query parameters must include an API key, a token, the name of the list AND the id of the Board you would like to create a list in.

Scroll down to the example section and copy the url.

All right, let's get back to Postman!

Alt Text

Step 3: Open a new tab in Postman
The tab of postman you have used to send a create a board request should be visible. Click on the + sign to create a new tab.

Step 4: In the new tab, change the HTTP method to POST

Step 5: Copy and paste the url from Trello documentation in the url bar.
The url from the most current documentation(as of 8/14/2020) should the following:
https://api.trello.com/1/lists?key=0471642aefef5fa1fa76530ce1ba4c85&token=9eb76d9a9d02b8dd40c2f3e5df18556c831d4d1fadbe2c45f8310e6c93b5c548&name={name}&idBoard=5abbe4b7ddc1b351ef961414

Step 6: Update query params with your own API key, token, name of the list, AND the id of the Board you want to create the list in
Alt Text
In the key column, enter key, token, name and idBoard as shown in the image.

In the value column, copy and paste the api key and token you have saved previously in the appropriate row.

For the list name, name it "Ooh wanna go there?"

For idBoard, copy the id of the board we created from the previous tab and paste it here.

Step 7: Click send to submit the request to Trello API

Step 8: Assess the response you have received from Trello API in the body section(pink box)
Alt Text
You will see that an object with info about the list has been returned to you.

Task 3: Writing API tests using Postman

Test is a practice of comparing the value from the response against an expected value. In Postman, tests are only executed upon receiving a response from the server.

Alt Text

Click on Tests tab highlighted with red box. It will display the interface below.

Alt Text

On the right side, you will see a section titled SNIPPETS. These are code snippets of most commonly used API tests you can customize for your API.

Step 1: Learn how to use test snippet: Status code: Code is 200

Scroll down and select Status code: Code is 200 (green box). Upon selection, you will see that the following code snippet is displayed on the page(red box).

#test 1
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});
Enter fullscreen mode Exit fullscreen mode

Let's break this down.

pm.test
This is a Postman function that you call to write test specifications. All Postman tests begin with pm.test.

"Status code is 200"
The first parameter of pm.test function is the test name and this is usually a string. Since we are testing whether the status code is 200, the test name is titled as so.

  • function () {...}*
    The second parameter is a callback function that contains assertions.

  • pm.response.to.have.status(200)*
    This is an assertion. It specifies your expectations regarding response sent from the API. In this case, you expect the response to have a status of 200.

Let's put it all together! The Status code: Code is 200 snippet states "call pm.test function named Status Code is 200. Check if the response returns a status of 200. Simple huh?

Step 2: Learn how to use test snippet: Response body: JSON value check

Testing the status code is not enough to fully understand what exactly is happening with the API request we send.

What if we wanted to test if the list was created with a specific name or properties?

You can use Response body: JSON value check snippet(red box).
Alt Text

Clicking on the snippet should yield the following test(orange box).

pm.test("Your test name", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.value).to.eql(100);
});
Enter fullscreen mode Exit fullscreen mode

As you can see, this snippet is very similar to status 200 test we have just covered. Let's break down the callback function to bite sized pieces.

var jsonData = pm.response.json();

This line of code is declaring jsonData as a variable, which parses the API response to Javascript object.

Javascript object is shown in the bottom third of the screen(pink box). This object contains valuable information about a list we just created in our Trello board.

Alt Text

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

This line of code allows you to compare a value from an Javascript object to an expected value.

When you look at the Javascript object(pink box), you will see that there are multiple key value pairs.

To ensure that the correct list has been created, you can check whether the list created exhibits the correct name of the list. (yellow box).

When you look at the Javascript object, you will see that name of the list is contained in the key value pair of "name": "Ooh wanna go there? "

Let's write a test to see if newly created list has the name of "Ooh wanna go there?".

  1. In the first parameter of pm.test, name the test with the following: "Check if the list is correctly named"

  2. Locate pm.expect(...), place the key name after jsonData.

  3. In the parenthesis that comes after .eql, enter the value of "Ooh wanna go there?"

Your test should look like the following:

#test 2
pm.test("Check if the list is correctly named", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.name).to.eql("Ooh wanna go there? ");
});
Enter fullscreen mode Exit fullscreen mode

Let's write one more test before running the tests!

In Trello, you can create multiple boards. What if you want to make sure that the list has been created within a specific board? Can you guess what test you need to write to check if this is true?

Try it on your own and compare your answer to solution below!

#Test 3
pm.test("Check if the list has been created within designated board", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.idBoard).to.eql("5f3709ddfc5a9068eb2b821c");
});
Enter fullscreen mode Exit fullscreen mode

Explanation
When we send a post request to create a list, we include the id of the board we want to create a list within as a query parameter. When you send a post request, you get a javascript object with key of idBoard(green box). This is the id of the Board that list was created in.
Alt Text

In order to check if the list was created in the right board, simply check if the value of idBoard property of the list is equal to the id of the board you want the list to be created in.

Step 3: Run three tests by clicking on send button

This action will send the post request again to the Trello API. Once the API response has been received, Postman will run three tests we have written.

Step 4: View the test results

See the test results tab highlighted with a red star?
The parenthesis shows you how many tests have been passed. Click on Test Results

Alt Text

Clicking on Test Results will yield the following page.

Alt Text

It shows that all tests have passed, meaning we were able to successfully create a list with the right name within the right board!

Step 5: Make the test fail by changing the expected value to a wrong one

You would be surprised how often developers create tests that will never fail! What's the point of creating a test that cannot tell the difference between right values and the wrong values, right?

While writing tests, it is a good practice to test whether the test could be failed.

Let's use "Check if the list is correctly named" test for example. I am purposely going to change "Ooh wanna go there? "Ooh wanna go there?!!!!! " as an example to see if the test could pick up that I have the wrong value for the list name.

pm.test("Check if the list is correctly named", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.name).to.eql( "Ooh wanna go there?!!!!! ");
});
Enter fullscreen mode Exit fullscreen mode

Let's run the test again by clicking on send button.

Alt Text

Yaaaas!! The wrong value for list name yielded a failed test result. Now you know that your tests are solid and you can trust it to pick up suspicious activity in your API.

There you have it!

You have now mastered the basics of navigating through Trello API and writing API tests in Postman. To get more practice, try the following challenges on your own!

Challenge 1:
Create and delete a card from a list and write your own tests to check if everything worked.

Challenge 2:
Move the card from one list to another and write your own tests to check if everything worked.

alt giphy

Discussion

pic
Editor guide
Collapse
kathryn0908 profile image
Katie Clark

Thanks, Lisa! Love this, I am going to check out Trello!

Collapse
lisahjung profile image
Lisa Author

Aw you are so welcome Katie. Thank you for making my day. :)