How to Test an API Using Python and JavaScript

If you're looking for tips on testing an application programming interface (API) with Python or JavaScript, you're in the right place.

It’s a thin line between choosing an application programming interface (API) and deciding whether you can work with it or not. Most REST APIs have a generic architecture and thread a common request path. But some APIs out there deviate from the standard. Consequently, they become difficult to use.

Thus, before building your entire software on an API, you need to perform quality checks and ensure it’s working fine. So what’s API testing, and how can you test an API?

What Is API Testing?

API testing involves the initial assessment of an API’s functionality, security, scalability, speed, and more to see if it’s ideal for the program that wants to use it. But superficially, it may involve testing to see if it sends the appropriate responses when you make requests through its various endpoints.

Depending on its structure, while testing an API, you’ll make requests (Get, Post, Update, or Delete) to its relevant endpoints. There are many metrics to check during API testing. But at a beginner level, you want to validate an API’s integrity from its status code and ensure that it fetches and accepts the correct data.

To that end, like any web request, an API might return the 200, 400, or 500 status code or even others.

Most APIs use JSON responses to serve their payloads. Depending on the goal, others may accept and respond with XML, multipart, or HTML payloads.

How to Test an API Using Python and JavaScript

Although there are many graphical user interface (GUI) API testing tools on the internet, you can assess an API more critically with written scripts.

An API tells in its documentation the kind of requests it allows and provides relevant endpoints to them. So you can grab and test them using the appropriate request methods.

Unlike the actual production phase, API testing is crude. So you don’t need as much specificity as you would while running the API for production. Although there are different types of API testing, we’ll focus more on response validation tests in this article.

We’ll test a fake store API in this tutorial using JavaScript’s fetch and Python’s requestslibrary. While doing this, we’ll test endpoints for getting, posting, updating, and deleting data.

How to Test a Get API Endpoint With JavaScript

Like you would use it in production, you can test an API in JavaScript using either Axios or the fetch method.

To get the response status from the API using fetch:

fetch('https://fakestoreapi.com/products',
  ).then(res =>{
    
    console.log(res)
})

The above request returns a 200 status if it’s a valid response. Once you make a successful request, you can then request real-time data from the API.

Let’s get the data from this API:

fetch('https://fakestoreapi.com/products',
  ).then(res =>{
    if (res.ok){
    return res.json()
}
}).then(response=>{
    console.log(response)
}).catch(err => console.log(err))

The response to the above fetch code looks like this:

To get the price of all products, for instance, you can use the map function:

fetch('https://fakestoreapi.com/products',
  ).then(res =>{
    if (res.ok){
    return res.json()
}
}).then(response=>{
    response.map(data =>{
        console.log(data.price)
    })
    // console.log(response)
}).catch(err => console.log(err))

The above logs the following output:

Testing a Get Endpoint With Python

As mentioned earlier, Python also uses the requests library to access an API’s data.

To check the status of the response in this case:

import requests 
data = requests.get('https://fakestoreapi.com/products')
print(data.status_code)

Logging data as we did above returns a corresponding status. It’s 200 in this case, though.

Now let’s get the same data with Python as we did while using JavaScript:

import requests
data = requests.get('https://fakestoreapi.com/products')
myData = data.json()
print(myData)

The result of the above looks like this:

You can get specific data using the for loop.

To get product prices, for instance:

import requests
data = requests.get('https://fakestoreapi.com/products')
myData = data.json()
indexes = 0
for i in myData:
    goods = myData[indexes]
    indexes +=1
    print(goods["price"])

Here’s what the output looks like:

Testing a Post Endpoint With JavaScript

After testing and seeing that the Get request works, depending on your aim and what the API offers, you might want to check if you can insert data into it, too.

In contrast to how you make a Get request, a Post request accepts a payload. Plus, you’ll need to specify that it’s a Post request:

// Specify the payload 
let payload = {
    title: 'new product',
    price: 13.5,
    description: 'test description',
    image: '',
    category: 'electronic'
}

fetch('https://fakestoreapi.com/products',
{
    method: "Post",
    headers:{
        'Content-Type': 'application/json'  
    },
    body: JSON.stringify(payload) //convert the payload to JSON 
}
  ).then(res =>{
      if (res.ok){
    console.log(res.status)
    return res.json()
}
}).then(response => {
    console.log(response)
}).catch(err => console.log(err))

The above code logs the response status code and the new information inserted when you run it. This tells you if your request went through or not. Typically, if the status code is 200, then your API has a valid endpoint that returns the appropriate response.

Testing Post Request With Python

You can also test a post endpoint of an API using Python’s requests.post. As you did while using JavaScript’s fetch, you need to specify the payload here as well:

import requests
payload = {
    'title': 'new product',
    'price': 13.5,
    'description': 'test description',
    'image': '',
    'category': 'electronic'
}
Posted = requests.post('https://fakestoreapi.com/products', 
data = payload
)
print(Posted.status_code)
print(Posted.json())

Like JavaScript, the above Python code also logs the response status code and the new data specified within the payload.

Testing the Put Endpoints

Updating API data takes the same process as posting and getting them in both languages.

To do this using JavaScript’s fetch, you only need to replace Post with Put:

// Specify the payload
let payload = {
    title: 'new product',
    price: 13.5,
    description: 'test description',
    image: '',
    category: 'electronic'
}

fetch('https://fakestoreapi.com/products/19',
{
    method: "Put",
    headers:{
        'Content-Type': 'application/json'  
    },
    body: JSON.stringify(payload) //convert the payload into JSON
}
  ).then(res =>{
      if (res.ok){
    console.log(res.status)
    return res.json()
}
}).then(response => {
    console.log(response)
}).catch(err => console.log(err))

If you pay attention to the API endpoint, you’ll see that it includes the product ID this time. This is how the API knows what data you want to update in this case.

Nonetheless, some APIs might use other methods to craft their endpoints. So that’s not a standard.

To test API data update using Python, you use requests.put instead:

import requests
payload = {
    'title': 'new product',
    'price': 13.5,
    'description': 'test description',
    'image': '',
    'category': 'electronic'
}
Posted = requests.put('https://fakestoreapi.com/products/19', 
data = payload
)
print(Posted.status_code)
print(Posted.json())

The above examples, if successful, insert the new data into position 19 as indicated by the API endpoint.

Testing the Delete Request

Deleting data from an API is as easy as making a Get request. That’s because, unlike Post and Put, you don’t need to specify any payload. All you need is the delete endpoint.

Our chosen API here uses the product ID to track its data. So, deleting a product is easy:

fetch('https://fakestoreapi.com/products/19',
{
    method: "Delete",
    headers:{
        'Content-Type': 'application/json'  
    }
}
  ).then(res =>{
      if (res.ok){
    console.log(res.status)
    return res.json()
}
}).then(response => {
    console.log(response)
}).catch(err => console.log(err))

You only need a few lines of code to achieve the same thing using Python:

import requests
Posted = requests.delete('https://fakestoreapi.com/products/19', 
)
print(Posted.status_code)
print(Posted.json())

Both examples above log the response status code and data belonging to the queried id (19 in this case).

Are These Testing Methods Generic?

While we’ve only focused on a single API in this post, the methods used to test the CRUD endpoints aren’t different when dealing with other APIs. The only difference, of course, might be in the rules surrounding each API structure and guidelines for requesting data. Once you decipher these for a chosen API, you can then use the appropriate method, as described here, to test its corresponding endpoints.

Exit mobile version