How to test an API using Python and JavaScript

0

There is a thin line between choosing an application programming interface (API) and deciding whether you can use it or not. Most REST APIs have a generic architecture and a common request path. But some APIs deviate from the standard. Therefore, they become difficult to use.

So, before you build your entire software on an API, you need to perform quality checks and make sure it is working properly. So what is API testing and how can you test an API?

What is API testing?

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

Depending on its structure, when testing an API, you will make requests (Get, Publish, Update, or Delete) to its relevant endpoints. There are many metrics to check when testing APIs. But at a beginner level, you want to validate the integrity of an API from its status code and make sure that it retrieves and accepts the correct data.

For this purpose, like any web request, an API can return the status code 200, 400 or 500 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

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

An API indicates in its documentation what type of requests it allows and provides them with relevant endpoints. So you can retrieve and test them using the appropriate query methods.

Related: What Is REST API and How Can You Retrieve Data for Your App or Website?

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

We are going to test a fake store API in this tutorial using JavaScript go look for and Python requests library. In doing so, we will test the endpoints to get, publish, update, and delete data.

How to test a Get API endpoint with JavaScript

As you would use in production, you can test an API in JavaScript using either Axes or the go look for method.

To get the status of the API response using go look for:

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

console.log(res)
})

The above query returns a 200 status if it is a valid response. Once you have made 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 recovery code looks like this:

Screenshot showing Fetch get response

To get the price of all products, for example, you can use the menu 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 records the following output:

Screenshot showing the price response for the JavaScript API test

Test a Get endpoint with Python

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

To check the status of the response in this case:

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

Registration The data as we did above returns a corresponding status. It’s 200 in this case, however.

Now let’s get the same data with Python as with 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 responding to data using Python

You can get specific data using the 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 the price response using a Python query for testing

Test a publish endpoint with JavaScript

After testing and finding that the To have request works, depending on your purpose and what the API offers, you might want to check if you can insert data into it as well.

Unlike the way you make a To have request, a To post request accepts a payload. Additionally, you will need to specify that this is 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 inserted when you run it. This tells you whether your request was successful or not. Typically, if the status code is 200, your API has a valid endpoint that returns the appropriate response.

Test the publish request with Python

You can also test an API endpoint using Python requests.post. Like you did using JavaScript go look for, you also need to specify the payload here:

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 new data specified in the payload.

Testing sales endpoints

Updating API data requires the same process as publishing and getting it in both languages.

To do this using JavaScript go look for, you just need to replace To post with To 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, this time you will see that it includes the product ID. This is how the API knows what data you want to update in this case.

However, some APIs may use other methods to create their endpoints. It is therefore not a standard.

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

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

Testing the deletion request

Removing data from an API is as easy as making a Get request. This is because, unlike Post and Put, you don’t need to specify a payload. All you need is the removal endpoint.

The API we chose here uses the product ID to track its data. Thus, deleting a product is simple:

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())

The two examples above record the response status code and data pertaining to the queried ID (19 in this case).

Are these test methods generic?

Although we’ve only focused on one API in this article, the methods used to test CRUD endpoints are no different when dealing with other APIs. The only difference, of course, might be in the rules surrounding each API structure and the guidelines for requesting data. Once you’ve decrypted them for a chosen API, you can then use the appropriate method, as described here, to test its corresponding endpoints.

So, since each API has rules for connecting to it, so during testing, some may provide additional parameters to include in your request headers. These settings typically include an access token or others, as noted in the documentation.


what-api
What does API mean? Examples of API usage

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

Read more


About the Author


Source link

Leave A Reply

Your email address will not be published.