This forum uses cookies
This forum makes use of cookies to store your login information if you are registered, and your last visit if you are not. Cookies are small text documents stored on your computer; the cookies set by this forum can only be used on this website and pose no security risk. Cookies on this forum also track the specific topics you have read and when you last read them. Please confirm that you accept these cookies being set.

Http request
#1
I am struggling a litte bit with understanding what is going wrong here:

Code:
function set_light_state(id, is_on)
    local url = base_url .. 'devices/' .. id
    local payload = json.encode({
        {
            attributes = {
                isOn = is_on
            }
        }
    })

    response_body = {}
    local _, code = https.request{
        url = url,
        method = "PATCH",
        headers = {
            ["Authorization"] = "Bearer " .. access_token,
            ["Content-Type"] = "application/json"
        },
        source = ltn12.source.string(payload),
        sink = ltn12.sink.table(response_body),
        verify = false
    }

    -- Check respnse
    if code == 200 then
        log('Light was set to ' .. (is_on and 'på' or 'av'))
    else
        log('Error updating light state. Status code: ' .. tostring(code))
        log('Server response: ' .. table.concat(response_body))
    end
end


The server throws an error when using this function. The response is not helpful as it seems like an internal server error.

I am guessing it has something to do with the payload, as the curl opposite of this function works fine:

Code:
curl -X PATCH "https://{IP}}/v1/devices/{ID}" \
              -H "Authorization: Bearer BEARER_TOKEN" \
              -H "Content-Type: application/json" \
              -d '[{"attributes":{"isOn":true}}]' \

Is the payload formatted correctly as in the curl?
Reply
#2
You are missing Content-Length header:
Code:
["Content-Length"] = #payload,
Reply
#3
That did the trick, thank you!
Reply


Forum Jump: