httpService:PostAsync() ERROR 401 when trying to reach OpenAI api

Hey, im currently trying to reach OpenAI’s responses endpoint but it seems to always give me an Error 401 Unauthorized while still providing a valid api key that has Permission set to all.

i have tried using other services like Openrouter to reach an different ai api’s of course changing my code accordingly to it but it always ends up giving me a 401 Unauthorized error.

this is the api documentation for the endpoint im trying to reach:
API Reference - OpenAI API

local url = "https://api.openai.com/v1/responses"

local headers = {
	["Authorization"] = "API-KEY"
}

local data = {
	["model"] = "gpt-4.1",
	["input"] = "test"
}
httpService:JSONEncode(data, headers)
httpService:PostAsync(url, data, Enum.HttpContentType.ApplicationJson, false, headers)

my friend has been trying to work with the gpt chat api for quite some time and shared the code, I’m not sure if it will work to be honest.

local HttpService = game:GetService("HttpService")
local apiKey = "Bearer YOUR_API_KEY" -- Replace YOUR_API_KEY with your actual key
local url = "https://api.openai.com/v1/chat/completions"

local headers = {
	["Authorization"] = apiKey,
	["Content-Type"] = "application/json"
}

local data = {
	model = "gpt-3.5-turbo", -- or "gpt-4" if your key has access
	messages = {
		{ role = "user", content = "Hello, how are you?" }
	}
}

local jsonData = HttpService:JSONEncode(data)

local response
local success, err = pcall(function()
	response = HttpService:PostAsync(url, jsonData, Enum.HttpContentType.ApplicationJson, false, headers)
end)

if success then
	print("Response: ", response)
else
	warn("Request failed: ", err)
end

Thanks for sharing, at first i thought it might has been the Content-Type but as in the tutorial i watched about JSON & httpservice it does not need to be provieded and isnt even accepted surprisingly in the header itself.

the code is pretty similar to mine the only difference is uses a pcall for the function i tried it just in case but it also gave me the same error.

Make sure that the HTTP requests enabled in place settings.
Also try in real game(join through roblox application)

If it doesn’t work, then maybe the api requires some kind of technology or other means that Roblox does not supports.

My best guess is currently that either roblox or openai blocks such requests as i cant find any solution to the problem.

This is not an isolated case. I found the tutorial and there are messages about the “401 error”

Cant seem to find a fix i followed documentation arcordingly.

It doesn’t look like there is a solution to this problem. You can try contacting openai support or using another AI (as an option: gemini 2.0 flash, the AI from Google, seems to have no restrictions on requests)