Have you ever deployed a static site, but found yourself in need of an API endpoint? Perhaps you needed somewhere to post form data, but the thought of setting up your own server, manage the endpoint and write the logic seemed like too much work. Not anymore
3 min read
·
By Sindre Moldeklev
·
December 1, 2019
I recently created a static webpage and needed an API endpoint. The page was a simple landing page, with a contact form where potential clients could reach out.The choice of hosting for the site fell on Netlify, and they just happen to have a super simple way of utilizing AWS Lambda Functions.
In this post, I will show you how to setup an API endpoint for whatever your heart desires in three simple steps.
For the three steps, there are some prerequisites that needs to be met:
netlify-cli
with npm install -g netlify-cli
.netlify init
and follow the prompt in the terminal.With netlify-cli
installed, go ahead and make a new function with the following command
netlify functions:create <name_of_your_function>
This will trigger a prompt with a few different function templates provided by Netlify. For this demonstration I chose hello-world
.
Open your function in your editor of choice. You may use the template and just skip ahead to step 3 if you want to, or you can switch out the template content with your own logic. I will add the following code which fetches a random quote by Donald Trump on every request. Pay attention to the fact that if you use the Donald Trump example you will have to run npm init
and install axios with npm install axios --save
to have a working example.
const axios = require("axios");
async function getRandomQuote(cb) {
const response = await axios.get("https://api.tronalddump.io/random/quote");
cb(response.data);
}
exports.handler = function (event, context, callback) {
getRandomQuote((data) => {
callback(null, {
statusCode: 200,
body: JSON.stringify(data),
});
});
};
Using the netlify
command, you can easily test your function locally. Just run netlify dev
and follow the instructions in your terminal.
The last step we should do is make our endpoint available on the internet. This is as simple as running git push
with your committed changes. Netlify will deploy your site and after a few seconds you will have an available API endpoint. To get to the admin panel of your site, run netlify open
in your terminal. Your endpoint will be available at https://<yoursitename>.netlify.com/.netlify/function/<your_function_name>
.
In this short post, we have seen how easy it is to get started with Netlify functions. With just a few commands using the netlify-cli
we have created an api endpoint where you can implement your own logic easily.
Now go ahead and make something awesome!
Loading…
Loading…
Loading…