0

I have a template for a Python function that calls an API and returns data. I'd like to run load testing against that API using locust.

import requests

proxies = {"http" : None,
           "https" : None}

verify = "/data/certs/abc123.crt"


def call_api(par1, par2, par3):


    r = requests.post(url = 'https://ABCD123.XYZ.QWERTY:9010/public/api/v1/ABC_TEST/query',
                      json = {"par1" : par1, "par2" : par2, "par3" : par3}, verify = verify, proxies = proxies)
return r

How could I translate this into a locust class?

user263961
  • 47
  • 1
  • 4

1 Answers1

0

I do it this way:

# prepare the headers to send to the remote host
headers = {"key":"value",
           "key":"value"}

# prepare the data for the POST body
data = {"key":"value",
        "key":"value"}```

with connection_object.client.post(url, headers=headers, 
    json=data, name=task_name, catch_response=True) as response:
    # convert the response to JSON
    msg = json.loads(response.content.decode('utf-8'))
    if response.status_code == 200:
        # we got a 200 OK
        response.success()
    else:
        response.failure("failure text")

In this example, this code runs in a separate function called from the UserBehavior class, so connection_object is "self" if you are doing this inside the task in the class.

In your example though, change

r = requests.post(url = 'https://ABCD123.XYZ.QWERTY:9010/public/api/v1/ABC_TEST/query',
                      json = {"par1" : par1, "par2" : par2, "par3" : par3}, verify = verify, proxies = proxies)

to


class UserBehavior(SequentialTaskSet):
    @task()
    def task1(self):
        r = self.client.post('https://ABCD123.XYZ.QWERTY:9010/public/api/v1/ABC_TEST/query', 
    json = {"par1" : par1, "par2" : par2, "par3" : par3}, 
    verify = verify, proxies = proxies)

I am sure you have seen this, which shows "get", but not "post". If you are unfamiliar with the requests library, it can get confusing. Hope that helps!

Chris Hare
  • 161
  • 2
  • 12