Testing a JSON API


This is a basic example which uses the http and json load script APIs to test a JSON API server.
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))

Feedback and Knowledge Base