How do I call a netlify function through the client side using a simple function invocation like NetlifyFuction()?

I have an API that want to access whenever a user clicks on a certain state on the US Map. I’d like to get the state id (ex: CA) and send it to the netlify function.
The netlify function would then get everything I need from the API and return it to the client side js file I have.
Is this possible?

Hey Scott!

Yes indeed!

Assuming that you’re able to write whatever you need in the client-side JavaScript to handle the click, determine which state had been selected, and then make a request to suitable endpoint, then the rest of this would live in a Netlify Function.

Whenever you create a Netlify Function, Netlify will provision it for you behind the scenes and then give it a URL that you can use to invoke it. The URL is gets will be relative to the root of your site’s domain like this:

https://yoursite.com/.netlify/functions/FILE-NAME-OF-YOUR-FUNTION (without the file extension)

I think that using HTTP GET (rather than POST) would suit your use case, so perhaps the request you’d make to the Netlify function might look something like this:

https://yoursite.com/.netlify/functions/getStateInfo?state=THE-STATE-CODE

Then your Netlify Function could get the state from the querystring parameter, do whatever API lookup it needed to do, and return the data to the client-side code which requested it.

Here’s a good example of a serverless function which makes a request to an API to lookup weather information related to the lat/long data passed to it via a querystring. I bet that is close to what you’d need.

Does that answer your question?

1 Like