Pass query parameters to a url inside a lambda function

I want when a user submit a search form to add the query parameter to the api endpoint that is inside a lambda function.
I set up the netlify environment inside a react app and initialize a lambda function.Now I only get the response using hard-coded queries.
const URL = ${API_URL}search?part=snippet&maxResults=5&key=${API_TOKEN}&q=animals

How can I pass parameters to the event.queryStringParameters?

Hi @paoup, thanks for writing in!

You need to pass the query parameters in via the request made from your frontend. You said that you get the response when using hard-coded queries, do you mean the variables you are passing in have no value? If so then that sounds like an issue with your code. Did you check if those variables have the expected values in your UI before you pass them to the function?

Hi @futuregerald thanks for replying!
I use the token-hider template in the function and I have already set up the environmental variables correctly.

exports.handler = function(event, context, callback) {
  const API_PARAMS = qs.stringify(event.queryStringParameters);
  const { API_TOKEN, API_URL } = process.env;
  const URL = `${API_URL}?${API_PARAMS}&key=${API_TOKEN}`;

  // Let's log some stuff we already have.
  console.log("Injecting token to", API_URL);
  console.log("logging event.....", event);
  console.log("Constructed URL is ...", URL);

  const pass = body => {
    callback(null, {
      statusCode: 200,
      body: JSON.stringify(body)
    });
  };

  // Perform the API call.
  const get = () => {
    axios.get(URL, {
          params: {
            q: 'cars'
          }
      })
      .then(response => {
        console.log(response.data);
        pass(response.data);
      })
      .catch(err => pass(err));
  };
  if (event.httpMethod == "GET") {
    get();
  }
};

I try to test the api call but the URL cannot be constructed correctly - it injects the url and the token variables but the q parameter doesn’t get passed into the endpoint. Am i missing something?

Can you share the URL you are using to try and trigger this function? Please include an example of the query params you are passing (you can replace the values with fake ones).

1 Like