OpenCloud via HttpService Post Issues

I am trying to write a system for OpenCloud datastore manipulation, and I am not sure what to post into the body for creating an entry, or updating it, so if anyone could help that would be awesome!

I’ve looked over the docs but they aren’t very specific when it comes to Luau code.

function OpenCloudDatastore:_createEntryForPlayer(player)
	local postUrl = string.format(
		"https://apis.roblox.com/cloud/v2/universes/%s/data-stores/%s/entries?id=%s",
		HUB_UNIVERSE_ID,
		DATASTORE_NAME,
		player.UserId
	)

	local body = {
		value = HttpService:JSONEncode(PROFILE_TEMPLATE),
		users = { tostring(player.UserId) },
		attributes = {
			createdAt = os.time(),
			version = "v1",
		},
	}

	local bodyJSON = HttpService:JSONEncode(body)

	local success, response = pcall(function()
		return HttpService:PostAsync(postUrl, bodyJSON, Enum.HttpContentType.ApplicationJson, false, {
			["x-api-key"] = HttpService:GetSecret(X_API_KEY),
		})
	end)

	if success then
		return response
	else
		warn("Failed to create entry for player:", player.Name, "Error:", response)
		return nil
	end
end

Creating and updating the entry require two separate requests.
Creating is a POST, and updating is a PATCH (you’ll need HttpService.RequestAsync)

Creating

In the body of creating an entry, you need etag, value, attributes, and users. I see you’ve already got attributes and value, but users isn’t quite right. Instead of being a raw string, you need it in the form users/userid, so for you it’d be users/14326596. etag is just a unique resource identifier for this version of the data store entry, you could probably generate that how you want.

local success, response = pcall(HttpService.RequestAsync, HttpService, {
    Method = "POST",
    Headers = {
        ["content-type"] = "application/json",
        ["x-api-key"] = "your API key",
    },
    Body = {
        value = HttpService:JSONEncode(PROFILE_TEMPLATE),
        users = {"users/"..player.UserId},
        attributes = {
            createdAt = os.time(),
            version = "v1"
        },
        etag = "your unique etag"
    }
})

if (not success or response.StatusCode ~= 204) then
    warn("something went wrong.")
end

Updating

As previously mentioned, this requires a PATCH request - partially updating an already existing resource. It’s basically just the same thing but PATCH instead of POST. I’m pretty sure you can use the already existing etag.

POST | Create DataStoreEntry
PATCH | Update DataStoreEntry

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.