Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local json = loadfile("json")()
- APIClient = {}
- APIClient.__index = APIClient
- function APIClient.new(baseURL)
- local self = setmetatable({}, APIClient)
- self.baseURL = baseURL
- return self
- end
- function APIClient:get(endpoint)
- local url = self.baseURL .. endpoint
- local response = http.get(url)
- if not response then
- error("Failed to get response from server")
- end
- local jsonString = response.readAll()
- response.close()
- local ok, data = pcall(json.decode, jsonString)
- if not ok then
- error("Error decoding JSON: " .. data)
- end
- return data
- end
- function APIClient:post(endpoint, data)
- local url = self.baseURL .. endpoint
- local headers = {
- ["Content-Type"] = "application/json"
- }
- local jsonData = json.encode(data)
- local response = http.post(url, jsonData, headers)
- if not response then
- error("Failed to post data to server")
- end
- local jsonString = response.readAll()
- response.close()
- local ok, result = pcall(json.decode, jsonString)
- if not ok then
- error("Error decoding JSON response: " .. result)
- end
- return result
- end
- return APIClient
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement