PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Where is the International Space Station?

Where is the International Space Station?

Sep 27 2018, 2:04 AM PST

This code sample uses HttpService’s GetAsync to make a request to an endpoint at Open Notify, a website that provides information from NASA. The endpoint provides information on the current location of the International Space Station. This example uses a defensive coding technique that you should use when making web requests. It wraps the call to GetAsync and JSONDecode in pcall, which protects our script from raising an error if either of these fail. Then, it checks the raw response for all proper data before using it. All of this is put inside a function that returns true or false depending of the request’s success.

Whenever you’re working with web requests, you should prepare for anything to go wrong. Perhaps your web endpoint changes or goes down - you don’t want your game scripts raising errors and breaking your game. You want to handle both success and failure gracefully - have a plan in case your data is not available. Use pcall and make plenty of validity checks (if statements) on your data to make sure you’re getting exactly what you expect.

local HttpService = game:GetService("HttpService")

-- Where is the International Space Station right now?
local URL_ISS = "http://api.open-notify.org/iss-now.json"

local function printISS()
	local response
	local data
	-- Use pcall in case something goes wrong
	pcall(function ()
		response = HttpService:GetAsync(URL_ISS)
		data = HttpService:JSONDecode(response)
	end)
	-- Did our request fail or our JSON fail to parse?
	if not data then return false end
	
	-- Fully check our data for validity. This is dependent on what endpoint you're 
	-- to which you're sending your requests. For this example, this endpoint is 
	-- described here:  http://open-notify.org/Open-Notify-API/ISS-Location-Now/
	if data.message == "success" and data.iss_position then
		if data.iss_position.latitude and data.iss_position.longitude then
			print("The International Space Station is currently at:")
			print(data.iss_position.latitude .. ", " .. data.iss_position.longitude)
			return true
		end
	end
	return false
end

if printISS() then
	print("Success")
else
	print("Something went wrong")
end