APIs are everywhere. From checking the weather on your phone to making online purchases, APIs are the silent helpers behind many of the services we rely on every day. But have you ever wondered how they work or how we make sure they’re doing their job correctly? That’s where API testing comes in.
If you’ve ever used an app or website and wondered how it pulls data from other services, like showing your social media feed or fetching product details from a database, it’s likely using an API. Testing these APIs is crucial to ensuring they function smoothly and securely.
In this blog post, we will explore how to test REST API methods so let's look at them in more detail.
So, What API is Afterall?
In simple terms, an API Application Programming Interface is a set of rules that allows different software applications to talk to each other. Imagine you’re at a restaurant. You (the user) are placing an order (request) to the waiter (the API), and the waiter takes that order to the kitchen (the server), which sends back your food (response). This entire process happens whenever you use an app or website that pulls data or interacts with another system. There are several types of API’s. Let’s take a quick look.
Types of APIs You Should Know About
APIs come in different types, each with its own purpose and way of working. Here are a few:
- SOAP (Simple Object Access Protocol): This type of API is used for secure transactions and structured communication, and is often found in older systems.
- GraphQL: A newer type that allows you to request specific data from a server, making it more efficient for some use cases.
- gRPC: Used in systems that need fast and efficient communication between different services, like in large-scale systems.
- REST (Representational State Transfer): By far the most common type. REST APIs are simple, and flexible, and use standard HTTP methods like GET, POST, PUT, and DELETE to interact with data.
HTTP Methods: What They Do
Once you’re familiar with the types of APIs, it’s time to understand how they communicate. API endpoints use HTTP methods to define what action you want to perform. Here’s a quick rundown:
- GET: Get data from the server (e.g., fetching a list of users).
- POST: Send data to the server (e.g., submitting a form).
- PUT: Update existing data (e.g., editing a user profile).
- DELETE: Remove data (e.g., deleting an account).
What Are API Endpoints?
Next, let’s explore the key component of any API request: the endpoint. Endpoints are like doorways that connect to the data you want from an API. Every time you make a request to an API, you’re essentially knocking on one of these doors. The API will send you the information you asked for, as long as you know where to knock (the URL) and have the right permission (headers and parameters).
An End Point Request URL can be constructed as below:
Base URL/resource/(Query/Path)Parameters
Let’s understand API endpoints in detail:
Base URL:
The term “Base URL” refers to the root address of a web application that remains consistent across different pages of a website.
Example: https://www.google.com
Resources:
Resources represent specific collections or a set of data in an API that can be accessed and altered through requests from the server.
Example:
https://www.google.com/map - map resource will help you to access the map API.
Query Parameters:
It is used to sort or filter the resource. Query parameters are identified with “?” and separated by “&.”
Example: https://amazon.com/orders?date=2020-02-20&sort_by=desc
Path Parameters:
Path parameters are variable parts of a URL path. It is a sub-resource that keeps on changing with every API request. They are typically used to point to a specific resource within a collection, such as a user identified by ID.
Example: https://www.google.com/Images/1123343 (After / the ID is a path parameter.)
Example: Most commonly used API headers include:
Authorization: The purpose of this header is to authenticate requests. Different types of authorization include Basic auth, OAuth, JWT bearer, api key, bearer token.
The token-based authentication is often represented by the keyword Bearer followed by the access token Bearer you_access_token; this ensures that the request has the necessary permissions to access the API.
Content-Type: It defines the format of the request body, such as application/JSON or application/xml, which helps the server interpret the data.
Why Test API Endpoint?
APIs are designed to do specific tasks, and the way an app works depends on APIs to get the right response. Sometimes, a single action in an app calls several APIs at once. If one of these APIs breaks, it can cause the whole system to fail and the app might stop working properly.
APIs also handle sensitive information, like login details, and testing them helps ensure that unauthorized users can't access private data or perform actions they shouldn't be able to. Since many different apps might use the same API, a problem with one API can affect several apps at once. This makes testing APIs essential to prevent issues from reaching the users.
For example, think about the payment API on an online shopping site. When a customer is ready to check out, this API handles their payment. If there's a mistake with the payment API, the customer might not be able to complete the purchase, which could lead to lost sales and unhappy customers. A failure in the payment API doesn’t just affect one customer; it could stop everyone from completing their orders.
Testing API Endpoints:
API testing can be achieved both manually and automatically. The choice between manual and automated testing depends on several factors, such as the project’s requirements, how complex the API is, how often the API needs testing, the time available, and the extent of testing needed.
For instance, if we require frequent testing of API endpoints in deployments or builds, we could opt for automated testing, and if the project involves some unique test cases that don’t require testing often, then we can opt for manual testing.
Similarly, if the API goes through regular updates that require continuous validation to catch regressions, then automating the API could be the optimal option, and if frequent changes are not required, then we can select the latter.
Let's take a look at how to perform API testing using Postman.
Why Postman?
Postman is a widely popular tool used by many organizations. It facilitates both manual and automated tests using Javascript. Its user-friendly interface makes it easy to set up and allows even less experienced beginners to interact with the API’s without digging into details to make requests, analyze the responses, and debug issues against it.
Postman also allows us to arrange our requests by organizing them into collections and adding tests to verify the responses from your API. We can also create environments to store different API endpoint setups and shift between them easily.
Here's a step-by-step guide to walk you through the process:
Step 1: Download and Install Postman
- Visit the Postman website and download the application that is compatible with your operating system.
Step 2: Setup your Environment
- Once Installed, open Postman and click on the Environment button from the left panel.
- Click on the Add button to create a new Environment and provide a name for your Environment (e.g. Development, Staging, or Production).
- Define your necessary Environment variables for instance baseURL, api_key, access_token, refresh_token etc.
Step 3: Create your Collection
- To create a Collection, click on the “new” button choose a collection from the options, and provide a name to your collection e.g. API tests.
Step 4: Add Request
- To add a request to your collection, click on the “Add request” located under the dotted dropdown button next to your collection name.
- Provide a name to your request and select the type of the HTTP method of your request (e.g. GET, POST, PUT, DELETE).
- Enter the endpoint request URL or use environment variables for dynamic URLs (e.g. {{base_url}}/resource).
- Add all necessary parameters (e.g. api-key), headers such as application/json , Authorization bearer_token, and request payload body required depending upon the type of HTTP method of your API.
- Save your request, click on the send button to Request and the Server sends the response back.
- For a successful request, you’ll receive a status response of 200 ok.
Step 5: Writing Test Scripts
Scripts in Postman allow us to write tests that validate the response data, status data, or other conditions to check if an API request is returning correct results.
- Go to the Scripts tab of your request.
- Use JavaScript to write tests that will validate your response. Here is an example of a script that validates the response status returned as 200.
Step 6: Run Collection
Once we have created multiple requests within our collection, we can use the Collection Runner to execute them sequentially. For this purpose,
- Click the three dots button at the right side of your collection name and select Run Collection.
- Under the Run configuration header, specify the number of iterations and delay between requests and data files (if required).
- Click the run collection button at the bottom to execute your request.
- Each request will be executed in the order they are listed in the collection, analyze the results, and ensure all tests pass.
Conclusion:
API testing is an important part of making sure applications work well, are secure, and run smoothly. By understanding the basics of APIs, methods, and endpoints, and using tools like Postman, you can easily test your APIs and find problems early in your development process. This guide will help you get started with API testing in Postman, ensuring better quality and confidence in your development projects.