Advertisement
mathiaas

api_client

Apr 21st, 2024 (edited)
574
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.21 KB | None | 0 0
  1. local json = loadfile("json")()
  2. APIClient = {}
  3. APIClient.__index = APIClient
  4.  
  5. function APIClient.new(baseURL)
  6.     local self = setmetatable({}, APIClient)
  7.     self.baseURL = baseURL
  8.     return self
  9. end
  10.  
  11.  
  12. function APIClient:get(endpoint)
  13.     local url = self.baseURL .. endpoint
  14.     local response = http.get(url)
  15.     if not response then
  16.         error("Failed to get response from server")
  17.     end
  18.  
  19.     local jsonString = response.readAll()
  20.     response.close()
  21.     local ok, data = pcall(json.decode, jsonString)
  22.     if not ok then
  23.         error("Error decoding JSON: " .. data)
  24.     end
  25.  
  26.     return data
  27. end
  28.  
  29.  
  30. function APIClient:post(endpoint, data)
  31.     local url = self.baseURL .. endpoint
  32.     local headers = {
  33.         ["Content-Type"] = "application/json"
  34.     }
  35.     local jsonData = json.encode(data)
  36.     local response = http.post(url, jsonData, headers)
  37.     if not response then
  38.         error("Failed to post data to server")
  39.     end
  40.  
  41.     local jsonString = response.readAll()
  42.     response.close()
  43.     local ok, result = pcall(json.decode, jsonString)
  44.     if not ok then
  45.         error("Error decoding JSON response: " .. result)
  46.     end
  47.  
  48.     return result
  49. end
  50.  
  51.  
  52. return APIClient
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement