Knowledgebase

Testing a JSON API


This is a basic example which uses the http and json load script APIs to test a JSON API server. Since testing API endpoints typically has slightly different requirements than testing an app or website. We also suggest our article on How to load test an API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
local username = "xxxxx"
local password = "yyyyyyy"

local data, headers, response



data = json.stringify({email=username, password=password})
headers = {
    ["Content-Type"] = "application/json"
}
response = http.request({"POST",
        "https://api.xxxx.com/login",
        headers = headers,
        data = data,
        response_body_bytes=1000000})

if response.status_code ~= 200 then
  log.error('login API error')
  do return end
end

-- read response value
local token = json.parse(response.body).token.key



headers = {
  ["Content-Type"] = "application/json",
  ["Authorization"] = "Token "..token
}
response = http.request({"GET",
  "https://api.xxxx.com/v3/account",
  headers = headers,
  response_body_bytes=1000000})

if response.status_code ~= 200 then
  log.error('fetching API error')
  do return end
end


log.debug(response.body)
data = json.parse(response.body)
--process data


client.sleep(math.random(20, 40))