In this article, we introduce a tool for testing APIs. Locust is one of the tools that provides the capability to send a large number of requests. To use Locust, we can utilize its Docker image and create a Python file named "locustfile.py" where we define the necessary commands to send requests to the API.

To run Locust, you can use the following docker-compose.yml file:

version: '3'
services:
  master:
    image: locustio/locust
    ports:
     - "8089:8089"
    volumes:
      - ./:/mnt/locust
    command: -f /mnt/locust/locustfile.py --master -H http://master:8089

  worker:
    image: locustio/locust
    volumes:
      - ./:/mnt/locust
    command: -f /mnt/locust/locustfile.py --worker --master-host master

Alongside the docker-compose.yml file, you also need to create the locustfile.py file. The locustfile.py file should include:

from locust import task, between
from locust.contrib.fasthttp import FastHttpUser
from random import randint
import xml.etree.ElementTree as ET

class MyUser(FastHttpUser):
    wait_time = between(5, 20)

    @task
    def index(self):
        URL="http://yourwebsite.com/api/v1/Users"
        with self.client.get(URL, name="DotNetDocs") as response:
            pass

In the locustfile.py file, we have specified that requests should be sent to the address http://yourwebsite.com/api/v1/Users.

Now, if you execute the command:

docker-compose up

and go to the address http://127.0.0.1:8089, you will see the Locust dashboard, and you can perform the Load Test operations.

If you want to add headers to your requests, you can do so as follows:

from locust import task, between
from locust.contrib.fasthttp import FastHttpUser
from random import randint
import xml.etree.ElementTree as ET

class MyUser(FastHttpUser):
    wait_time = between(5, 20)

    @task
    def index(self):
        URL="http://yourwebsite.com/api/v1/Users"
        with self.client.get(URL, name="DotNetDocs", headers={"Authorization":"Bearer YourJwtToken"}) as response:
            pass

In the above section, the Authorization header will be added to the requests sent to the API endpoint api/v1/Users.

If you execute the docker-compose.yml file on your system and want to send requests to your localhost, you need to change the host address to host.docker.internal (more information):

from locust import task, between
from locust.contrib.fasthttp import FastHttpUser
from random import randint
import xml.etree.ElementTree as ET

class MyUser(FastHttpUser):
    wait_time = between(5, 20)

    @task
    def index(self):
        URL="http://host.docker.internal/api/v1/Users"
        with self.client.get(URL, name="DotNetDocs", headers={"Authorization":"Bearer YourJwtToken"}) as response:
            pass

Additionally, you can change the number of workers for sending requests at the time of building the Docker container:

docker-compose up --scale worker=12

;)

Powered by Froala Editor

Comments