Created
June 26, 2022 13:54
-
-
Save leemartin/602c433b604400e247bfce84271de0ff to your computer and use it in GitHub Desktop.
Apple WeatherKit REST API Netlify Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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