Skip to content

Instantly share code, notes, and snippets.

@leemartin
Created June 26, 2022 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leemartin/602c433b604400e247bfce84271de0ff to your computer and use it in GitHub Desktop.
Save leemartin/602c433b604400e247bfce84271de0ff to your computer and use it in GitHub Desktop.
Apple WeatherKit REST API Netlify Function
const axios = require("axios")
const jwt = require("jsonwebtoken")
const handler = async (event) => {
try {
// Decode private key
const privateKey = Buffer.from(process.env.WEATHERKIT_KEY, 'base64').toString()
// Get team, key, and app id
const teamId = process.env.WEATHERKIT_TEAM_ID
const keyId = process.env.WEATHERKIT_KEY_ID
const appId = process.env.WEATHERKIT_APP_ID
// Sign jwt token
const jwtToken = jwt.sign({}, privateKey, {
jwtid: `${teamId}.${appId}`,
issuer: teamId,
expiresIn: "1h",
subject: appId,
header: {
alg: "ES256",
kid: keyId,
id: `${teamId}.${appId}`
}
})
// Get coordinates from parameters
const latitude = event.queryStringParameters.latitude || 29.951065
const longitude = event.queryStringParameters.longitude || -90.071533
// Get current weather from WeatherKit
const { data } = await axios.get(`https://weatherkit.apple.com/api/v1/weather/en/${latitude}/${longitude}?dataSets=currentWeather&timezone=US/Pacific&countryCode=us`, {
headers: {
"Authorization": `Bearer ${jwtToken}`
}
})
// Return weather
return {
statusCode: 200,
body: JSON.stringify(data)
}
} catch (error) {
// Return error
return {
statusCode: 500,
body: error.toString()
}
}
}
module.exports = { handler }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment