roblox httpservice guide

Roblox HttpService Guide

Using Roblox HttpService for HTTP requests allows you to add third-party services to your game when you need more advanced computation or real-time data, error reporting, or other communication methods. 

Roblox also allows you to use your own remote servers to control your games using the HttpService. Imagine controlling your game features using a web service without having to publish another build to Roblox.

HTTP Requests for beginners

The web is built on HTTP requests. Every time your browser goes to a website it uses HTTP requests to communicate with the site’s servers and databases. 

HTTP stands for Hyper Text Transfer Protocol. Using what is known as REST (short for REpresentational State Transfer), a site or application can get and send data to a web server.

Each request has a few ways of working with data. We can use request headers, the request body, or request parameters.

Ever wonder what all that extra stuff you see in some URLs? Those are query parameters. 

Request headers inform the server and the client app of various technical needs such as data formats, how current or fresh is the data along with so much more. 

For example, REST APIs may respond with a Content-Type header set to application/json. This means we’re working with JSON data.

It’s best to review the documentation of any API before starting to implement your HTTP client. Some may default to an XML response when it’s easier to work with JSON. 

These parameters will vary with each third-party API since there’s no industry standard. Great APIs follow best practices and provide easy to understand documentation.

roblox httpservice security

Protect your data with REST API security

Security is vital to protect the data that the API is responsible for. We can use secret keys and tokens or even usernames and passwords to guard the data. 

Requests use authentication to confirm the request is coming from a valid application or user. Once a request is authenticated, an API endpoint can validate if it’s authorized to complete the action.

Authentication confirms and validates that you are who you say are.

Authorization confirms and validates that your account has the right level of access to complete an action.

Some APIs use cookies to pass along data between the client and server, although this isn’t too common or as secure.

OAuth is one of the best authentication methods since its tokens give granular access control. If you’ve used sign-in with Google or sign-in with Facebook buttons then you’ve used OAuth. OAuth tokens can easily grant specific permissions without revealing a user’s sensitive information such as their password. 

Working with Caches

Ever repeatedly loaded a website expecting to see something new? We’ve all done this when trying to buy a product that’s in limited supply. You can blame the cache when it doesn’t update fast enough.

REST APIs cache their responses for various performance reasons. The cache contains data that has already been requested and makes it available without having to repeat the original data flow again. The client application can bypass the cache but the server has the ultimate control for often you’ll receive the latest data.

Caches exist along the entire client to server stack. 

  • Client app can cache data locally to avoid making unnecessary requests
  • The API server can use memory caches to control how often the database is used
  • The API database can cache queries to limit how often it executes expensive transactions

A Content Delivery Network such as CloudFront is a caching service that allows a single origin server to make its content available worldwide. When someone visits your site or uses your app, they will communicate with servers closer to them, which dramatically speeds up the response time for data requests.

build your roblox REST API

Create a REST API

REST APIs use several methods that include GET, POST, PUT, and DELETE request methods. 

These different methods are used for creating, reading, updating, and deleting data (known as CRUD for short) from your database. 

It’s best practice to follow RESTful conventions where:

  • GET method retrieves data
  • POST method sends new data
  • PUT method updates data
  • DELETE method remove data

If you’re just getting started with creating your own REST API then I would recommend checking out the serverless framework. This will get you started by focusing mainly on the functionality of your API without having to deal with the actual servers themselves. 

With the serverless framework, you can use Python or even Javascript / Node to quickly get your APIs up and running. Your Cloud provider of choice (Google Cloud, Amazon Web Service, Microsoft Azure) sets up your API using metered services instead of actual servers that you’d need manage. There’s no need to worry about server OS security or having to update a large group of servers yourself, your Cloud infrastructure service takes care of it.

Of course, once your API becomes a core piece of your project, you should consider using more cost effective infrastructure services.

API services you can use

The possibilities are endless with APIs and how you can use them.

Before you start reviewing any third-party API, you should use a HTTP client such as Postman to review how these APIs work. This will save you time since you can test different endpoints and parameters before writing your client code in Roblox.

If you prefer a purely open-source API tool, then check out Insomnia.

Ever wanted to use real weather data in your game? You could use a free weather API such as OpenWeather. Imagine having your world in sync with real weather.

Maybe you want to add a random joke in your message of the day. Check out the Geek Joke API. What if you occasionally use a random joke in your NPCs dialog?

Play free music from SoundCloud.

Create a fantasy sports team game using real sports statistics with the Fantasy Sports API.

Add some fun Jeopardy trivia by using the jService API.

Connect Roblox HttpService with REST APIs

Now that we have a good fundamental understanding of REST APIs, let’s write a Roblox HTTP client.

Enable HttpService

For unpublished games, set the HttpEnabled boolean property to true on HttpService.

local HttpService = game:GetService("HttpService")
HttpService.HttpEnabled = true

Update the HttpEnabled option in your Roblox Studio game settings.

Working with JSON data

Most modern REST APIs use a data format known as JSON. JSON (short for Javascript Object Notation) is similar to a Lua table. We can use the HttpService:JSONEncode function to transform or convert a Lua table to JSON format.

local someTable = {
  someNumber = 100,
  someText = “Hello”,
  someOtherObject = {
    anotherNumber = 200,
    Enabled = true
  }
}
local jsonData = HttpService:JSONEncode(someTable)
-- [[ jsonData becomes
{
   "someNumber": 100
     "someText": “Hello”,
     "someOtherObject": {
       "anotherNumber": 200,
       "Enabled": true
     }
 }
-- ]]

Roblox blocks all network port numbers below 1024 except for the standard web ports for http (port 80) and https (port 443). Blocked ports will return a 403 Access Forbidden error when used.

Each Roblox server is only allowed to send 500 requests per minute. This comes out to around 8 requests per second. When this limit is exceeded, the game server will yield for 30 seconds. 

To get around this, your scripts can use their own queue to send requests in small batches. This is especially important when there’s a lot of players triggering these requests.

Make a GET request

Let’s get a random geek joke from the Geek Jokes API.

You will get a JSON response that includes one field

{"joke": "Chuck Norris does not eat. Food understands that the only safe haven from Chuck Norris' fists is inside his own body."}
local HttpService = game:GetService("HttpService")
local jokeURL = "https://geek-jokes.sameerkumar.website/api?format=json"
local response = HttpService:GetAsync(jokeURL)
local data = HttpService:DecodeJSON(response)
if data.joke then
  -- response successful
  print(data.joke)
end

Make a POST request

Let’s use the mock TO-DO API to create a to-do list. HttpService:PostAsync defaults to the JSON content type.

local HttpService = game:GetService("HttpService")
local postTodoURL = "https://jsonplaceholder.typicode.com/posts"
local todoBody = {
  title = "first to-do",
  body = "to-do description",
  userId = 1
}
local postBody = HttpService:EncodeJSON(todoBody)
local response = HttpService:PostAsync(postTodoURL, todoBody)
local data = HttpService:DecodeJSON(response)

Using other REST methods

We’ll use the HttpService:RequestAsync function to use other REST methods.

Let’s update a to-do that we created using the POST method.

local HttpService = game:GetService("HttpService")
local todoURL = "https://jsonplaceholder.typicode.com/posts/1"
local todoBody = {
  title = "updated title",
  body = "to-do description",
  userId = 1
}
local postBody = HttpService:JSONEncode(todoBody)
local response = HttpService:RequestAsync({
  Url = todoUrl,
  Method = "PUT"
})
local data = HttpService:JSONDecode(response)

Roblox HTTP Client script

Here’s a base client you can use and extend for any API.

local HttpService = game:GetService("HttpService")

HttpClient = {}
function HttpClient:new(baseUrl)
  local o = {}
  o.BaseUrl = baseUrl or ""
  self.__index = self
  return setmetatable(o, self)
end

function HttpClient:GetAsync(path)
  local url = self.BaseUrl .. path
  local response = HttpService:GetAsync(url)
  Return response
end

-- encode table to JSON and decodes response to lua table
function HttpClient:PostAsync(path, data)
  local url = self.BaseUrl .. path
  local postBody = HttpService:JSONEncode(data)
  local response = HttpService:PostAsync(url, postBody)
  local responseData = HttpService:JSONDecode(response)
  return responseData
end

function HttpClient:PutAsync(path, data)
  local url = self.BaseUrl .. path
  local body = HttpService:JSONEncode(data)
  local response = HttpService:RequestAsync({
    Url = url,
    Method = "PUT",
    Body = body
  })
  local responseData = HttpService:JSONDecode(response)
  return responseData
end

function HttpClient:DeleteAsync(path)
  local url = self.BaseUrl .. path
  local response = HttpService:RequestAsync({
    Url = url,
    Method = "DELETE"
  })
  local responseData = HttpService:JSONDecode(response)
  return responseData
end

Here’s an example script using HttpClient.

local client = HttpClient:new("https://jsonplaceholder.typicode.com")
local newTodo = client:PostAsync("/posts", {
  title = "first to-do",
  body = "to-do description",
  userId = 1
})

newTodo.title = “updated todo title”
local updatedTodo = client:PutAsync("/posts/1", newTodo)

Using HttpService with Roblox plugins

Roblox Studio plugins can use HttpService to enhance their capabilities. A plugin can download additional data, track anonymous usage to improve plugin development, or anything else you can think of.

For example, the Rojo plugin creates its own local server to communicate with a code editor such as Visual Studio Code

Note that Roblox Studio protects its users by prompting for permission to communicate with outside services.

How Roblox could enhance HttpService

It would be great if Roblox servers could use webhooks. With a webhook, we could push data to our game to broadcast a message to all players. Imagine using fun tweets or other social media posts within a game. 
I can’t wait to see what Roblox does with their Open Cloud API.

What’s next

Now you have an understanding of how to add your own REST API or other third-party APIs. Use this new knowledge with your own Roblox game currency or your own creative API ideas. 

You could also track game statistics to share with your players within the game or on your web site.

Please consider joining my email newsletter for other Roblox related updates!

Thank you for reading and stay curious!

Leave a Reply

%d bloggers like this: