How to optimize my api usage

Im creating a system where each time i roll it will use the item id to go look for the detail (rap, default value) etc though i need to make it so i only use this api call once because if not i will get the error Too many requests

local function batchProcessItemDetails(itemIds)
	local itemDetailsUrl = "https://www.rolimons.com/itemapi/itemdetails"
	local batchSize = 100  -- Number of items to process per batch
	local numItems = #itemIds
	local rapValues = {}

	-- Iterate over items in batches
	for i = 1, numItems, batchSize do
		local batchIds = {}
		for j = i, math.min(i + batchSize - 1, numItems) do
			table.insert(batchIds, itemIds[j])
		end

		local batchIdsStr = table.concat(batchIds, ",")
		local apiUrl = itemDetailsUrl .. "?itemids=" .. batchIdsStr

		local success, response = pcall(HttpService.GetAsync, HttpService, apiUrl)
		if success then
			local decodedResponse = HttpService:JSONDecode(response)
			if decodedResponse and decodedResponse.items then

				for _, itemId in ipairs(batchIds) do
					local itemData = decodedResponse.items[tostring(itemId)]
					if itemData then
						local rap = itemData[3] or 0  -- Default to 0 if RAP is missing
						table.insert(rapValues, rap)
					else
						table.insert(rapValues, 0)  -- Placeholder for missing item data
					end
				end
			else
				warn("Invalid item details response for batch:", response)
			end
		else
			warn("Failed to retrieve item details for batch:", response)
		end
	end

	return rapValues
end

api https://www.rolimons.com/itemapi/itemdetails

1 Like

Try this:

local HttpService = game:GetService("HttpService")
local cachedItemDetails = {}  -- Cache for item details
local itemDetailsUrl = "https://www.rolimons.com/itemapi/itemdetails"
local batchSize = 100  -- Number of items to process per batch
local rapValues = {}

local function getItemDetails(itemId)
	if cachedItemDetails[itemId] then
		return cachedItemDetails[itemId]
	else
		local apiUrl = itemDetailsUrl .. "?itemids=" .. itemId
		local success, response = pcall(HttpService.GetAsync, HttpService, apiUrl)
		if success then
			local decodedResponse = HttpService:JSONDecode(response)
			if decodedResponse and decodedResponse.items then
				cachedItemDetails[itemId] = decodedResponse.items[tostring(itemId)]
				return cachedItemDetails[itemId]
			else
				warn("Invalid item details response for item ID:", itemId)
			end
		else
			warn("Failed to retrieve item details for item ID:", itemId)
		end
	end
end

local function batchProcessItemDetails(itemIds)
	local batchSize = 100  -- Number of items to process per batch
	local numItems = #itemIds
	local rapValues = {}

	-- Iterate over items in batches
	for i = 1, numItems, batchSize do
		local batchIds = {}
		for j = i, math.min(i + batchSize - 1, numItems) do
			table.insert(batchIds, itemIds[j])
		end

		-- Process batch
		for _, itemId in ipairs(batchIds) do
			local itemData = getItemDetails(itemId)
			if itemData then
				local rap = itemData[3] or 0  -- Default to 0 if RAP is missing
				table.insert(rapValues, rap)
			else
				table.insert(rapValues, 0)  -- Placeholder for missing item data
			end
		end
	end

	return rapValues
end


-- Example

local itemIds = {1028606, 1037673, 1048338}
local rapValues = batchProcessItemDetails(itemIds)
for i, rap in ipairs(rapValues) do
	print("Item ID:", itemIds[i], "RAP Value:", rap)
end

Here is the output:

Screenshot 2024-04-21 180258

Hope this helped

1 Like

when i do it, it prints out

 19:11:49.723  Failed to retrieve item details for item ID: 1532396  -  Server - RollServer:51
  19:11:49.812  Failed to retrieve item details for item ID: 1533893  -  Server - RollServer:51
  19:11:49.900  Failed to retrieve item details for item ID: 1563352  -  Server - RollServer:51
  19:11:49.992  Failed to retrieve item details for item ID: 1594180  -  Server - RollServer:51
  19:11:50.084  Failed to retrieve item details for item ID: 1861997  -  Server - RollServer:51
  19:11:50.172  Failed to retrieve item details for item ID: 2264398  -  Server - RollServer:51
  19:11:50.268  Failed to retrieve item details for item ID: 2799053  -  Server - RollServer:51
  19:11:50.357  Failed to retrieve item details for item ID: 3271938  -  Server - RollServer:51
  19:11:50.446  Failed to retrieve item details for item ID: 4765323  -  Server - RollServer:51
  19:11:50.534  Failed to retrieve item details for item ID: 4765718  -  Server - RollServer:51

and then continues for all the itemIds to error

I tried to put some of your ids and everything worked:

Screenshot 2024-04-21 181703

do you want the full script its kinda long though

Is your script local or your script is in server?

server but it has a few remote events

Maybe you should show me the whole script

task.wait(3)

local HttpService = game:GetService("HttpService")
local ReplicatedStorage = game:GetService('ReplicatedStorage')
local rollFunc = ReplicatedStorage.RollFunc
local rollR = ReplicatedStorage.Roll
local Chances = require(script.Chances)
local itemRarities = require(script.ItemsRarities)
local recivedLim = game:GetService('ReplicatedStorage').RecivedLimited


local success, response = pcall(HttpService.GetAsync, HttpService, "https://api.rolimons.com/players/v1/playerassets/1")
if not success then
	warn("Failed to retrieve player assets:", response)
	return
end

local data = HttpService:JSONDecode(response)
if not data or not data.playerAssets then
	warn("Invalid player assets data:", response)
	return
end

local newAssets = {}
for id, _ in pairs(data.playerAssets) do
	table.insert(newAssets, tonumber(id))
end
table.sort(newAssets)
-- Define function to batch process item details and retrieve RAP values
local cachedItemDetails = {}  -- Cache for item details
local itemDetailsUrl = "https://www.rolimons.com/itemapi/itemdetails"
local batchSize = 100  -- Number of items to process per batch
local rapValues = {}

local function getItemDetails(itemId)
	if cachedItemDetails[itemId] then
		return cachedItemDetails[itemId]
	else

		local apiUrl = itemDetailsUrl .. "?itemids=" .. itemId
		local success, response = pcall(HttpService.GetAsync, HttpService, apiUrl)
		if success then
			local decodedResponse = HttpService:JSONDecode(response)
			if decodedResponse and decodedResponse.items then
				cachedItemDetails[itemId] = decodedResponse.items[tostring(itemId)]
				return cachedItemDetails[itemId]
			else
				warn("Invalid item details response for item ID:", itemId)
			end
		else
			warn("Failed to retrieve item details for item ID:", itemId)
		end
	end
end

local function batchProcessItemDetails(itemIds)
	local batchSize = 100  -- Number of items to process per batch
	local numItems = #itemIds
	local rapValues = {}

	-- Iterate over items in batches
	for i = 1, numItems, batchSize do
		local batchIds = {}
		for j = i, math.min(i + batchSize - 1, numItems) do
			table.insert(batchIds, itemIds[j])
		end

		-- Process batch
		for _, itemId in ipairs(batchIds) do
			local itemData = getItemDetails(itemId)
			if itemData then
				local rap = itemData[3] or 0  -- Default to 0 if RAP is missing
				table.insert(rapValues, rap)
			else
				table.insert(rapValues, 0)  -- Placeholder for missing item data
			end
		end
	end

	return rapValues
end

-- Function to categorize items into rarity tiers based on RAP values
local function categorizeItemsByRarity(itemIds, rapValues)
	-- Clear existing categories in itemRarities module
	for rarity, _ in pairs(itemRarities) do
		itemRarities[rarity] = {}
	end

	-- Categorize items into rarity tiers based on RAP thresholds
	local numItems = #itemIds
	for i = 1, numItems do
		local itemId = itemIds[i]
		local rap = rapValues[i]

		if rap > 0 then
			if rap <= 5000 then
				table.insert(itemRarities.Common, itemId)
			elseif rap <= 10000 then
				table.insert(itemRarities.Uncommon, itemId)
			elseif rap <= 25000 then
				table.insert(itemRarities.Rare, itemId)
			elseif rap <= 50000 then
				table.insert(itemRarities.Epic, itemId)
			elseif rap <= 100000 then
				table.insert(itemRarities.Legendary, itemId)
			elseif rap <= 250000 then
				table.insert(itemRarities.Mythic, itemId)
			elseif rap <= 500000 then
				table.insert(itemRarities.Relic, itemId)
			elseif rap <= 1000000 then
				table.insert(itemRarities.Exotic, itemId)
			else
				table.insert(itemRarities.Stellar, itemId)
			end
		end
	end

end


local function processLimitedItems()
	local rapValues = batchProcessItemDetails(newAssets)
	categorizeItemsByRarity(newAssets, rapValues)
end


-- Call the function to process limited items and update itemRarities module
processLimitedItems()

local selectedCategorys = {}

local function performMultipleRandomRolls(assets, numRolls)
    local results = {}
    -- Clear selectedCategorys table before performing new rolls
    selectedCategorys = {}

    for _ = 1, numRolls do
        local totalWeight = 0
        local randomValue = math.random() * 161.1601  -- Assuming your probabilities are in percentages

        -- Determine the selected category based on the random value
        for _, category in ipairs(Chances) do
            totalWeight = totalWeight + category[2]
            if randomValue <= totalWeight then
                table.insert(selectedCategorys, category)  -- Insert entire category into selectedCategorys
                if #selectedCategorys > 5 then
                    table.remove(selectedCategorys, 1)  -- Remove the oldest entry if more than 5 categories are stored
                end
                break
            end
        end

        if selectedCategorys[#selectedCategorys][1] then
            -- Retrieve the appropriate list of item IDs based on the selected category
            local categoryItems = itemRarities[selectedCategorys[#selectedCategorys][1]]
            if categoryItems and #categoryItems > 0 then
                -- Select a random item ID from the category
                local randomIndex = math.random(1, #categoryItems)
                local selectedItemId = categoryItems[randomIndex]
                table.insert(results, selectedItemId)
            else
                table.insert(results, nil)  -- No items in the selected category
            end
        else
            table.insert(results, nil)  -- Invalid category selected
        end
    end

    return results
end



rollFunc.OnServerInvoke = function(player)
	local rolls = 5
	local selectedAssetIds = performMultipleRandomRolls(newAssets, rolls)

	-- Fetch item details
	local success1, response1 = pcall(HttpService.GetAsync, HttpService, "https://www.rolimons.com/itemapi/itemdetails")
	if not success1 then
		warn("Failed to retrieve item details:", response1)
		return
	end

	local decodedResponse = HttpService:JSONDecode(response1)
	if not decodedResponse or not decodedResponse.items then
		warn("Invalid item details response:", response1)
		return
	end

	local rapValues = {}
	local defValues = {}
	for i = 1, 5 do
		local itemId = selectedAssetIds[i]
		if itemId then
			local itemData = decodedResponse.items[tostring(itemId)]
			if itemData then
				local rap = itemData[3]
				local defValue = itemData[5]
				table.insert(rapValues, rap)
				table.insert(defValues, defValue)
			else
				table.insert(rapValues, 0) -- Placeholder if data is missing
				table.insert(defValues, 0)
			end
		else
			table.insert(rapValues, 0) -- Placeholder for nil asset ID
			table.insert(defValues, 0)
		end
	end

	-- Fire client event with results
	rollR:FireClient(player, selectedAssetIds,rapValues, selectedCategorys, defValues)	
end

I will start looking right now, thanks for the script!

1 Like

Can you please give me two scripts: Chances and itemsRarities (Not all, just two values for each i think it will be enough)

return {
	{"Common", 80, Color3.fromRGB(60, 60, 60)},  -- the rarity / the chance of getting /the color
	{"Uncommon", 55, Color3.fromRGB(0, 220, 0)},   
local module = {
	Common = {

	},
	
	Uncommon = {

	},

the item rarities gets filled through the rollServer script.it takes like 5 seconds because there 2500 items in there

1 Like

Thanks for these scripts! Now i will try again!

1 Like

Now i started to get these errors too:
Screenshot 2024-04-21 190756

do you have any idea on whats causing them

I thougth the ids doesnt but they are exist i found them, also i thought that the api doesnt work but it works. I think the problem is somewhere here (I could be wrong):

local function getItemDetails(itemId)
		if cachedItemDetails[itemId] then
			print(cachedItemDetails[itemId])
			return cachedItemDetails[itemId]
		else
			local apiUrl = itemDetailsUrl .. "?itemids=" .. itemId
			local success, response = pcall(HttpService.GetAsync, HttpService, apiUrl)
			if success then
				local decodedResponse = HttpService:JSONDecode(response)
				if decodedResponse and decodedResponse.items then
					cachedItemDetails[itemId] = decodedResponse.items[tostring(itemId)]
					return cachedItemDetails[itemId]
				else
					warn("Invalid item details response for item ID:", itemId)
				end
			else
				warn("Failed to retrieve item details for item ID:", itemId)
				warn("Error message:", response) -- Print the error message
			end
		end
	end

in my opinion i thinks it has to do with this

local apiUrl = itemDetailsUrl .. "?itemids=" .. itemId

but im not sure

I guess i found the problem. I maded a small func to check is there a cachedItemDetails[itemId]. Thats the func:

local function getItemDetailsV2(itemId)
		if cachedItemDetails[itemId] then
			print("Exists")
		else
			print("Nil")
		end
	end

And here is the output:
Screenshot 2024-04-21 192014

so what should i do?

(character limit)

It suddenly stopped replying…
Because it printed nil, this should run next:

local apiUrl = itemDetailsUrl .. "?itemids=" .. itemId
			local success, response = pcall(HttpService.GetAsync, HttpService, apiUrl)
			if success then
				local decodedResponse = HttpService:JSONDecode(response)
				if decodedResponse and decodedResponse.items then
					cachedItemDetails[itemId] = decodedResponse.items[tostring(itemId)]
					return cachedItemDetails[itemId]
				else
					warn("Invalid item details response for item ID:", itemId)
				end
			else
				warn("Failed to retrieve item details for item ID:", itemId)
				warn("Error message:", response) -- Print the error message
			end

But it doesnt run