Function Configuration
- Language: JavaScript
- Image:
node:20.13.1-slim
- Concurrency: Sync
- Environment Variables:
API_KEY
: Your API key for making external requests.
- Packages:
axios
: For making HTTP requests.dotenv
: For loading environment variables (optional if using a.env
file).
Function Code
This function takes a query parameter from the request, makes an external API call using the axios
package, parses the response, and returns a custom error message if something goes wrong. Otherwise, it returns a success message.
const axios = require('axios');
const handler = async (request) => {
const paramValue = request.params?.param_name;
if (!paramValue) {
return {
statusCode: 400,
body: "Missing 'param_name' in query parameters."
};
}
const apiKey = process.env.API_KEY;
const apiUrl = `https://api.example.com/data?query=${paramValue}&apiKey=${apiKey}`;
return makeExternalRequest(apiUrl);
};
const makeExternalRequest = async (apiUrl) => {
try {
const response = await axios.get(apiUrl);
return {
statusCode: 200,
body: JSON.stringify(response.data)
};
} catch (error) {
if (error.response) {
return {
statusCode: error.response.status,
body: `External API request failed: ${error.message}`
};
} else if (error.request) {
return {
statusCode: 500,
body: "No response received from external API."
};
} else {
return {
statusCode: 500,
body: `Request setup failed: ${error.message}`
};
}
}
};