Create a Mock API Endpoint Using Faker and Serverless

Lukas Ruebbelke
InstructorLukas Ruebbelke

Share this video with your friends

Send Tweet
Published 6 months ago
Updated 5 months ago

Mock APIs are useful for development when you can't use live data for whatever reason.

Faker makes creating mock APIs a straightforward process. In this lesson you'll see how to user Faker to create a generator object for each of a User's properties. Then we'll write a function that goes through each property and run a generate function.

Once we've created our mock API generator, we can use the Serverless framework to generate a Lambda Function and API Gateway so we can access our mock API from a live URL.

Instructor: [0:00] To reinforce how easy it is to take a JavaScript function and deploy it to an endpoint, we are going to build out something that I personally find to be incredibly useful. Generating a mock API that represents or stands in place for a real API when it becomes available.

[0:19] We're going to do this using faker and moment. As a result of the fact that we have npm packages, we're going to deploy this using serverless to save us a bunch of time. Inside of StackBlitz, the first thing that we're going to do is import faker.

[0:39] We're also going to import moment.js so that we can generate some dates. For a thought exercise, let's start with an interface. In this case, a user interface. You can see here that we have a number of properties that essentially establish a contract that we have to meet.

[1:00] Based on this interface, we're going to generate an array of user prompts. That means we're going to take the properties of the interface and create an array of strings that references those properties. From here, we are going to create a few utility functions.

[1:21] The first one is a function to generate a random integer between two predefined numbers. We'll pass in a min and a max, and then, using faker.datatype.number(), we're going to get a random number.

[1:38] Then we'll also generate a function that's going to create a random date. To do this, we'll use moment().subtract(), which will take this moment right here in time and then will subtract some amount of days from this also using random int.

[1:56] Finally, we're going to format this using an MM-DD-YYYY format. With that out of the way, we are going to create a HashMap that we're going to call Generators. This is a key-value pair that maps the key for the properties to a function that will generate a value for that particular property on that object.

[2:20] The first property that we're going to generate is for the ID. We'll generate a UUID so that, when we go look for that ID, it calls this function. Same thing for first name, we're going to use the First Name property on faker, so faker.name.firstName(). For the last name, we will use faker.name.lastName(). Now we'll start to build this out.

[2:46] One thing that we will introduce for a number of these particular properties, is that we need to pass in an argument. This is a second property on the param object that we're passing in. We have a function and we also have args. We've done title, notes, and progress.

[3:01] Let's also do active, which is of type Boolean, so true or false. Then we can also do a start date, which is going to call getRandomDate. This is really powerful because we can now create a generate function that takes in the props, as well as the generator's object.

[3:26] Then generate a new object and return it by iterating over the props array. Then for every prop, it will look up the generate function on the generator's object, and then populate that key in value on the object that we're generating.

[3:45] In this case, object prop using array notation. Then we're calling generator.func, or function, and then we're passing in generator args if it exists. Notice that this is called generate because we could really use this to generate anything, not just users.

[4:06] With that said, let's create a generate users method here and then pick a random number of users. We'll start with many users and max users. Then create a length property that calls getRandomIt, which is going to give us any number between 3 and 12 in this case.

[4:28] Next, we'll do something a little clever using ES6, which you will see when we generate the users array. We're going to call array.apply. Then create an empty array by passing in this length value. We can map over this empty array.

[4:46] For every empty element or space in this array, we can now return a generated user in its place. Also, at the end here, we will return the users array. Let's go ahead and update this call to update inner HTML. Let's add in the pretext so we get a pre-formatted block of markup.

[5:11] Then we'll call json.stringify, pass in the result of calling generated users. We'll add in null and to, to format the result. As you'll see, we have generated a random array of random users, which I could easily regenerate again here. You can see, it's completely different. One more time.

[5:35] This is the JavaScript that is necessary to generate a random collection of objects that we're going to use in our mock API once we deploy it. To that end, we'll open up the terminal and use it to generate a new serverless application or project.

[5:55] From the command line, sls create, we're going to use the AWS Node.js template. We're going to call this project "Egghead Mock API." Once this is created, we're going to step into the folder and open it up in VS code.

[6:13] You can see that within our project, we have our standard three files. If we look at the Handler.js, this is pretty standard. Let's go ahead and delete these two lines. From here, let's copy all of this code down to the last little bit, which we will skip.

[6:37] Then we will paste this in and we're going to get rid of this Typescript interface, which doesn't belong here. We'll go ahead and delete that, and save it. What we can do is update the handler here.

[6:54] We'll call this users and we'll update this call to JSON.stringify so that it calls generateUsers. Then let's clean up the output of this by putting in null and to. From here, we should install the dependencies for this project, npm i faker and moment.

[7:18] Now that these are installed, you'll see in the project that we have our node modules, package.json and our package-lock.json. Next, let's hop into our YAML and clean this up by deleting all of these comments. After that, let's change our function to users as well as our handler.

[7:40] We'll also want to add in an API gateway, so events. We're going to use the HTTP API. We'll set up our route or path to be API users, and our method will be git. We can deploy our project, so sls deploy.

[8:09] What this is going to do is to create the stack, but it's also going to generate some CloudFormation files. Generate everything into a zip, put it into S3, and deploy it. We can take this endpoint here, and copy it. Then let's open up a new tab in our browser and paste this in.

[8:32] We're going to let this run and you'll see now that from our browser, we're generating a random API. We can Refresh this a few times and see a different set of users every time.

[8:46] If we look inside of our Lambda serverless here, we can see that we have a mock API function here that we can step into and see. It comes with a function and a trigger. You'll notice that in the code source, we can't actually do any inline editing.

[9:08] That's because the dependencies are too large inside of the zip file, but what we can do is test this from the console. Let's create a test event. We will click Test and we'll see that the response is the same as what we observed in the browser.

[9:28] If we scroll up, we can see that we have an API gateway that's attached to this function that we're using to call the function, which we defined in the serverless YAML. Let's look over this code briefly.

[9:41] You'll notice that we took an interface and generated a user props array that we're iterating over and referencing the generator's HashMap and matching the key to a function that will generate a random value and assign that value to a property on the generated object.

[9:59] That is intentionally generic. On top of this, we have a specific function, generateUsers, which generates a custom collection of Bonk objects per our definition. From here, we're calling generateUsers and putting that into JSON.stringify.

[10:19] What I think is pretty interesting here is that we're only looking at about six lines of code for the server portion of this feature. We converted general-purpose JavaScript into a serverless app in about six lines of JavaScript an a few lines of YAML. Not bad for a day's work or in this case, about a 12 minute video.

[10:41] One last thing that I want to show you before we ride off into the sunset, is how to tear down the stack that we created. From the command line, we'll use sls remove.

[10:55] This will tear down the application stack that was defined in the serverless YAML. It's as easy as that. In the last 12 minutes, we learned how to very quickly define and deploy a mock endpoint into the Cloud using JavaScript functions.