How to test an API with Python and JavaScript

It’s a fine line between choosing an API and deciding whether or not you can work with it. Most REST APIs have a common architecture and follow a common request path. But some of the APIs out there deviate from the standard. Thus, it becomes difficult to use it.

Thus, before you build your entire software on the API, you need to do quality checks and make sure that it works well. So what is API testing, and how do you test an API?

What is API Testing?

API testing includes the initial evaluation of API functionality, security, scalability, speed, and more to see if it’s ideal for the program that wants to use it. But superficially, it might involve testing to see if it sends appropriate responses when requests are made through various endpoints.

Depending on its structure, while testing an API, it will make requests (get it, publish it, update it or delete it) to the relevant endpoints. There are many metrics to check during API testing. But at the entry level, you want to check the integrity of the API from its status code and make sure that it fetches and accepts the correct data.

To this end, like any web request, the API may return a status code of 200, 400, 500, or even other.

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

How to test an API with Python and JavaScript

Although there are many graphical user interface (GUI) API testing tools on the Internet, you can evaluate your API more accurately using written scripts.

The API tells in its documentation what kind of requests it allows and provides them with the relevant endpoints. So you can get it and test it using proper ordering methods.

Related Topics: What is a REST API and how do you get data for your app or website?

In contrast to the actual production stage, API testing is considered raw. So you don’t need as much specification as you do while running the production API. Although there are different types of API testing, we will focus more on response validation tests in this article.

We will test fake store API In this tutorial using JavaScript Bring and Python Orders library. While doing this, we will be testing endpoints to get, publish, update, and delete data.

How to test get an API endpoint using JavaScript

As if you were using it in production, you can test the API in JavaScript using either of them Axios or the Bring method.

To get response status from API using Bring:

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

console.log(res)
})

The above request returns a status of 200 if it is a valid response. Once you place 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 fetch code above looks like this:

Screenshot showing

To get the price of all products, for example, you can use a map Job:

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 records the following outputs:

Screenshot showing the price response for the JavaScript API test

Get an endpoint test using Python

As mentioned earlier, Python also uses the . file Orders Library for API data access.

To check the status of a reply in this case:

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

registration data As we did above return a corresponding case. 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:

Screenshot showing data response using Python

You can get specific data using a for loop.

To get product prices, for example:

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:

Screenshot showing price response using Python request for testing

Post Endpoint Test with JavaScript

After testing and seeing that file Get The order works, depending on your goal and what the API offers, you may want to check if you can enter data into it as well.

Unlike how to make a file Get request, a Mail Request accepts payload. Additionally, 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 records the response status code and new information entered when it is triggered. This tells you if your request has been fulfilled or not. Normally, if the status code is 200, your API has a valid endpoint that returns the appropriate response.

Test another request using Python

You can also test a later endpoint of an API using Python request.post. Like I did while using files Bring, you need to define 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 records the response status code and new data specified within a file payload.

Mode endpoint test

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

To do this using files BringAll you have to do is replace it Mail With Puts:

// 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, this time you’ll see that it includes the product ID. This is how the API knows what data to update in this case.

However, some APIs may use other methods to craft their endpoints. So this is not a standard.

To test update API data with Python, you can use requests. Input While that:

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, enter the new data at position 19 as indicated by the API endpoint.

Deletion request test

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

The API we chose here uses the product ID to track its data. So, deleting the 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 with Python:

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

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

Are these test methods generic?

While we only focused on one API in this post, the methods used to test CRUD endpoints are no different when dealing with other APIs. The only difference might, of course, be in the rules surrounding each API structure and instructions for requesting data. Once it has been decoded for a selected API, you can then use the appropriate method, as described here, to test their corresponding endpoints.

Thus, since every API has rules to call, so during testing, some may provide additional parameters for you to include in your request headers. These parameters usually include an access token or something else as provided in the documentation.


whats-api
What does API mean? Examples of how to use APIs

APIs are what allow programs and websites to “talk” to each other. Learn more about what APIs are and how to use APIs.

read the following


About the author

(Visited 9 times, 1 visits today)

Related posts