Overview
With LoadForge, testing GraphQL APIs becomes a breeze as you can utilize standard HTTP POST requests to send GraphQL queries.
In this documentation, we'll show you how to create a load test to query the missions from the publicly available SpaceX GraphQL API. The examples provided here can be adapted to test any GraphQL API. Furthermore, we'll cover how to authenticate your GraphQL requests.
Basic Example
First, let's start with a fundamental example. Here's a standard GraphQL query that requests the mission IDs and names from the SpaceX API:
{
missions {
id
name
}
}
Now, let's take a look at how you can implement this query for use in a LoadForge test. With this example, you'll see how straightforward it is to integrate your own GraphQL queries.
import time
from locust import HttpUser, task, between
class QuickstartUser(HttpUser):
wait_time = between(3, 5)
@task(1)
def index_page(self):
query = '''
{
missions {
id
name
}
}
'''
response = self.client.post(
"/graphql",
name="GraphQL",
json={"query": query }
)
Authenticating GraphQL Requests
In many instances, you may need to authenticate your requests to the GraphQL API. Here's how you can set custom headers for authentication:
response = self.client.post(
"/graphql",
name="GraphQL",
headers={
"Accept": "application/graphql",
"Authorization": "<Authorization-Token>"
},
json={"query": query}
)
If your testing requires obtaining an authorization token dynamically, you can automate this process with the on_start
method. This ensures that all the requests during your test have the required authentication header:
def on_start(self):
# Send a login request
response = requests.post("http://mysite.com/login", {"username": "user", "password": "pass"})
# Extract the "token" from the response header
self.client.headers.update({'Authorization': response.headers.get('token')})
Locust Test Example
LoadForge is built upon the robust foundation of Locust, which means that if you're already a user of the open-source Locust tool, you can directly use this script in your tests. If you're considering upgrading your testing capabilities, think about importing your Locust script to LoadForge and make the most out of your load testing efforts!