Use Netlify Functions to create a serverless function (also called a lambda function) that returns data in JSON format.
Jason Lengstorf: [0:00] Let's start by creating a new folder called functions, and inside of that we will create another folder called data, and inside of that we'll create products.json. Inside of that, we're going to add some JSON data for products.
[0:16] We've got two products here and each one has a sku, which is just a unique identifier, has a name, which is what we'll show as the product title, a description, which is some information about the product itself plus a photo credit. The image is an unsplash image. The amount is the price in pennies, so this is $10 or 1,000 cents. The currency is set to USD.
[0:41] We've got two of those. These are going to be our example products. We are going to treat this like a database, but you could load this from anywhere, from any data source.
[0:49] The reason this is in our functions folder is that we're going to be using serverless functions to serve it. The way that Netlify works, the functions folder gets deployed, so once it gets deployed, the functions inside of it won't have access to anything outside of the functions folder. That's why we're going to include the data here.
[1:08] The next thing that we want to do is create our first function. This is going to be called get-products.js. Inside of it, we're going to load our products from ./data/products.json, and then we will export a handler. The handler is going to be an async() function. We don't need any arguments this time. We're just going to return a statusCode of 200 for OK, and a body of JSON.stringify(products).
[1:45] Once we've saved this, we need to tell Netlify where to find the function. We're going to go back into netlify.toml. We're going to add functions = "functions" and that tells Netlify where to look for serverless functions.
[1:58] Once we've set the directory, we can start our server with ntl dev. This will load up the server for us, and then we can hit our function. The place that Netlify stores functions is /.netlify/functions, and then the name of our function which was get-products. When we run this, we get our JSON back.