Example tests and snippets

API Examples (GraphQL)

LoadForge is able to easily test GraphQL APIs using standard HTTP POST requests.

Below we have an example of a load test to query the missions from the open SpaceX GraphQL API. You can adapt this to test your own API. We also have more advanced uses below that.

Basic Example

Below is a standard GraphQL load test that requests mission ids and names from the Space X API. In specific the GraphQL query is:

{
  missions {
    id
    name
  }
}

Here is the implementation for use in a LoadForge test. You can see how easy it is to copy your own queries in.

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

You may need to authenticate against the GraphQL API, and you can do so by setting custom headers as shown in the partial snippet below.

    response = self.client.post(
        "/graphql",
        name="GraphQL",
        headers={
            "Accept": "application/graphql",
            "Authorization": "<Authorization-Token>"
        },
        json={"query": query}
)

You can also automate receiving an authorization token by setting an on_start declaration. This ensures that all your requests for the whole test have the custom header set.

    def on_start(self):
      # Send login request
      response = requests.post("http://mysite.com/login", {"username": "user", "password": "pass"})


      # set "token" from response header
      self.client.headers.update({'Authorization': response.headers.get('token')})

Locust Test Example

LoadForge is powered by locust, meaning open source locust users can copy this script as well. If you are a locust user, consider importing your script to LoadForge to supercharge your testing!

Previous
API examples (REST)