Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Roblox – Call external GraphQL API

I would like to call an external graphql API (without authentication for the moment).
Here is my code :

local open_api = "https://graphqlzero.almansi.me/api"

local payload = '{"query": "query { post(id: 1) { id title body }}"}'

local headers = {
}


local function craftCall()
    local response
    local data

  pcall(function ()
        response = HttpService:PostAsync(open_api, payload,  Enum.HttpContentType.ApplicationJson, false, headers)
        data = HttpService:JSONDecode(response)
    end)

    if not data then return false end

  print(data)
    return false
end 
    
    
    
if craftCall() then
    print("Success")
else
    print("Something went wrong")
end

I get always something went wrong. I need some help on what is going wrong… Specially I don’t know if am I correctly formatting the Payload.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

After your http call, you never return a success result. You’ve only outlined failure cases :

    if not data then return false end
    print(data)
    return false

So your conditional, if craftCall() then always evaluates to false.

Why not make it return true or data after the print(data)? Then you’ll know that it made it to the end of the call successfully.

local function craftCall()
    local success, result = pcall(function()
        local response = HttpService:PostAsync(open_api, payload,  Enum.HttpContentType.ApplicationJson, false, headers)
        return HttpService:JSONDecode(response)
    end)

    if not success then
        warn("PostAsync failed with error : ", result)
        return false
    end
    
    -- return the parsed data
    return result
end
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading