Using the HTTPService in Roblox


  • Using the HTTPService in Roblox

    The HttpService allows the server to make GET and POST requests which can be very beneficial to both the developer and the game itself.

    Some common example that use this service are:-

    • Trello module
    • Google Analytics
    • Other Google services
    • Server management and player counts per server

    Limitation of the HTTPService

    One of the main limitations of the HTTPService is that you are not able to send any requests to the Roblox site. This problem however can be resolved by having a third party request this information and then pass back any data requested which is a longer process. Some of the web api can be access via its reliant service e.g. any players id can be found by using GetNameFromUserIdAsync note this needs to be in a pcall.

    There is also a request limit of 500 per minute which far exceeds the request limitations of a DataStore(and key set limits)
    hence why it is the preferred method for creating a server management system. Lastly requests must have one of the following prefixes http:// or https:// other protocols are not supported.

    Making A Get Request

    A GetAsync request will return any data passed back from the server as a string, example:-

    -- note that the HTTPService muse be enabled
    local httpServ = game:GetService('HttpService')
    
    -- requests should be placed inside a pcall in case of errors
    local res, data = pcall(function()
          return httpServ:GetAsync('http://127.0.0.1') -- Loopback
    end)
    
    print('Request status', res, 'Data', data) 
    

    There are two possible errors that can occur excluding the limitations of the HTTPService which are:-

    • HTTP error codes (this applies to all request types) which are returned by the server to inform the client of why the request failed.
    • Unresolved host name, the url could not be resolved into a valid IP so the request cannot be sent.

    Making A POST Request

    By default PostAsync will set the content type to JSON which means that the data argument must be in a JSON format. The HttpService also includes JSONEncode and JSONDecode which are also useful outside of the HTTPService e.g. A DataStore stores tables in a JSON format so simply checking that you can encode the table with no errors will mean that the table can be saved.

    POST JSON Data Request
    The following PHP is setup to only process JSON data passed(server side):-

    <?php
    	// read the raw input
    	$json = file_get_contents('php://input');
    	// convert to JSON
    	$obj = json_decode($json);
    	echo var_dump($obj); // echo the variable
    ?>
    

    As the code above processes the JSON sent, we only need to encode our data as a JSON then send it with the request (client side):-

    local httpServ = game:GetService('HttpService')
    
    -- the data to send
    local data = {
    	user = 'test',
    	pass = 'pass1'
    }
    
    -- encode the data as a json 
    local sendData = httpServ:JSONEncode(data)
    while wait(2) do
    	local res, data = pcall(function()
                    -- add the data, no other settings are requiored as the default format is JSON
    		return httpServ:PostAsync('http://127.0.0.1', sendData) 
    	end)
    	
    	print('Request status', res, 'Data', data) 
    end
    

    POST Request
    Depending upon the server the data sent in the format of a JSON will not be accepted so we need to reformat the data being sent and change the HttpContentType as this informs the server what the content being sent is so it can be processed correctly.

    The following PHP code is setup to process a POST request:-

    <?php
            // if there is no post data use a empty string
    	$usr = isset($_POST['usr']) ? $_POST['usr'] : '';
    	$pass = isset($_POST['pass']) ? $_POST['pass'] : ''; 
             // return the data passed
    	echo 'user ' . $usr . ' pass ' . $pass;
    ?>
    

    We also need to process the data being sent to conform to this request type:-

    local httpServ = game:GetService('HttpService')
    
    local dataList = {
    	usr = 'aa',
    	pass = 'test'
    }
    
    -- return a post format string 
    local function createPost(tmp) 
    	local tmpStr = ''
    	for key, val in pairs(tmp) do
    		tmpStr = tmpStr .. key .. '=' .. val .. '&'
    	end
    	return #tmpStr == 0 and '' or tmpStr:sub(1,#tmpStr-1) 
    end
    
    local sendData = createPost(dataList)
    
    local url = 'http://127.0.0.1'
    while wait(3) do
    	local res, data = pcall(function() 
    		return httpServ:PostAsync(url, sendData, Enum.HttpContentType.ApplicationUrlEncoded) 
    	end)
    	
    	print('Request status', res, 'Data', data)
    end
    

    The code above formats the table into [variable name]=[value]& .... with the last & removed. We must also change the content type to ApplicationUrlEncoded which then allows the data to processed on the server and accessed using $_POST.

    Please comment and post any feedback, ile update this post if needed. I hope this helps to explain how the HTTPService in Roblox can be used.


  • Great job!


  • Good tutorial, will definitely come in handy while I keep forgetting how HTTPService works.

    One thing I did notice in your code for the GetAsync request is that you don't actually have GetAsync after the httpServ variable.


  • @Spongocardo Fixed, thanks for spotting this.

Log in to reply
 

Looks like your connection to Scripting Helpers was lost, please wait while we try to reconnect.