How would I be able to get the weather and temperature of NYC using HTTPService? I’m making a realistic game where it has the same time and weather as New York City does. All I need is an int/num value of the fahrenheight temperature of New York.
You can use existing weather APIs. This one might work. I did a simple search for “weather api” and this was the first result. Once you find an endpoint that gives you the information you want, you can use HTTPService:JSONDecode to turn the response from the API into a Lua table. You can then index the values you need from that table.
EDIT: Updated link to page that tells you more about what you need to do for your case.
How would I implement it to roblox is my question now.
-
First you need to create an API key for the service you’re using.
-
Make a Lua dictionary with the parameters available by the API that give you the best information for your use case. They should be listed under “request parameters” on the API documentation - your dictionary keys are the keys listed and the dictionary values are whatever values they take.
-
Use HTTPService:JSONEncode on your parameter table and HTTPService:SendRequest with the “GET” method to make a request to the web service. Make sure to wrap in a pcall in case it fails.
-
HTTPService:JSONDecode the response string from the SendRequest function to get back your Lua dictionary with the response parameters and use the information in whatever way you need.
This is how most RESTful web services work on the internet.
Since the free version of that only allows you to call it 50 times per day, here’s another free alternative. This doesn’t have a per-day limit, so it’s much less likely you’ll hit limits as long as you’re using it carefully.
Also, HTTPService:SendRequest isn’t a function. Did you mean RequestAsync?
-
Here’s my main post, to answer the original question in more detail:
First off, you’ll probably want to read the Roblox wiki article on RequestAsync, which you can find here: HttpService | Documentation - Roblox Creator Hub
Then, you’ll want an API key. I recommend Open Weather Map since their API is easy to use and they don’t have daily limits. You can get an API key here, you just need to sign up: How to start to work with Openweather API - OpenWeatherMap. Once you have your API key, which can be found on your account page you’ll want to look at the API, which you can find in my first link. Basically, you’ll need an ID for the city you’re looking for. You’ll have to manually search up what the ID for the city is, which you can do using their search tool. The id for the American city of New York, which I’m almost certain is what you’re looking for, is 5128581.
Putting this together, your API request might look something like this:
https://api.openweathermap.org/data/2.5/weather?id=5128581&appid=ABCDEF12345butlonger
Now that you know how to make a request to their API, you’ll need to learn how to do it on Roblox. Using RequestAsync is pretty simple, you just need to specify to URL you’re requesting data from and what HTTP method you want to use. In this case, we want to use the GET HTTP method, since you’re getting data from the site.
Then you have to worry about how Roblox formats the response. Calling RequestAsync returns one argument, which I’ll be calling response
. The raw JSON of the response is stored under response.Body
, which is what we’re most interested in. Before checking that, we’ll want to make sure the request was successful though. You can do that pretty simply: just check if response.Success
returned true.
If your HTTP request was successful, then response.Body
should have the JSON that the API request returned. Once you JSONDecode
it to get a Lua table, you might have a response like this:
Example JSON response
{
"coord": {
"lon": -74.01,
"lat": 40.71
},
"weather": [
{
"id": 701,
"main": "Mist",
"description": "mist",
"icon": "50n"
}
],
"base": "stations",
"main": {
"temp": 276.13,
"feels_like": 271.58,
"temp_min": 274.82,
"temp_max": 277.59,
"pressure": 1009,
"humidity": 93
},
"visibility": 9656,
"wind": {
"speed": 4.1,
"deg": 40,
"gust": 8.2
},
"clouds": {
"all": 90
},
"dt": 1577761838,
"sys": {
"type": 1,
"id": 5141,
"country": "US",
"sunrise": 1577708380,
"sunset": 1577741819
},
"timezone": -18000,
"id": 5128581,
"name": "New York",
"cod": 200
}
Some things about this might look off to you. For example, the temperature is 276 degrees. Fortunately, it’s not completely wrong. Although it might seem high, it was just formatted as Kelvins, for reasons unknown to me. Regardless, it’s a simple fix: the formula to convert Kelvins to degrees Fahrenheit is simple enough: degreesFahrenheit = kelvins * 9/5 - 459.67
. Fantastic! Now you have your final code, which should look something like this:
Final code
local httpService = game:GetService("HttpService")
local requestOptions = {
Url = "http://api.openweathermap.org/data/2.5/weather?id=" ..
"5128581" .. -- id for NYC
"&apikey=" ..
apiKey; -- YOUR API KEY GOES HERE! MAKE SURE TO CHANGE THIS!
Method = "GET";
}
local response = httpService:RequestAsync(requestOptions)
local responseBodyTable = httpService:JSONDecode(response.Body)
local function kelvinsToFahrenheit(temp)
return temp * 9/5 - 459.67
end
if response.Success then -- if it succeeded (your API key is valid)
local temperature = kelvinsToFahrenheit(tonumber(responseBodyTable.main.temp)) -- convert to fahrenheit
print("Temperature:", tostring(temperature) .. "°F") -- output the temperature
else
error(responseBodyTable.message) -- throw an error based on the response they gave
end
Output:
Temperature: 37.328°F
Great, there you go. It’s currently(?) 37 degrees Fahrenheit in NYC.
Edit: Simplified the conversion formula
Side Note: if you use open weather map it takes a couple of hours for a key to be activated ( at least for the free version, it’s not to long for what it’s worth though)
Thank you so much, you’ve simplified something that could have taken days. or even weeks to make. My next question is, how would you make it so that each server updates the temperature only twice a day, so that requests don’t send every time a new server opens.
If you are worried about it being “expensive” requesting the data/API , you shouldn’t be, but you could just set up a data store and recorded the results twice a day( use a counter), so it’s somewhat caching the HTTP results.
For example:
local DatastoreService = game:GetService("DatastoreService")
local Store = DatastoreService:GetDataStore("TemperatureData")
local Temperature = Store:GetAsync("New York")
if #Temperature < 2 then
--- request async, save it under a table or an normal numerical index
end
Hello there, may I know how to obtain weather data? It shows something like:
weather
Summary
[“id”] = xxx
I would like to find out how to obtain this ID, thanks!
Sorry for the bump by the way.
I don’t think you need to use the ID. It should have a description.
Just checking weather[1].main
here will give Mist, which is a good description of the weather. Not sure why it’s an array rather than directly stating the weather, but you can try some different API calls and see if it ever returns multiple elements in the array. Maybe it’s the same format for a full day forecast or something.
Where would I put the final code? ServerScriptService, StarterGui?
Also, how would I insert the api key? Would it be like apiKey; "keyhere"
?