Building basic API's with Express.js

––– views

By Max Campbell

So you want to build an API? This tutorial is going to show you how to build an API using Express.js & Node.js. Today you are going to build an API which returns images of art while automagically resizing them.

To get started clone the repo using:

Once you have done that you can open up your favorite text editor mine is vscode and open up the initial folder inside of that repo once you have done that run this to install the required packages:

Once you have installed all the packages you can startup the app using:

Now if you go to:

You should see 🖼 so we better get to work implementing the actual API!

Let's start by looking at the file tree:

As you can see it looks complicated but it's actually pretty simple now that you know a little bit more about how this works lets get started implementing the API.

Image.ts service:

So to get started where going to install sharp which is an image processing library with native bindings for better performance you can install it like this:

And then you can import it like this in the image.ts file under services/. Also make sure to import the filesystem into node!

So to implement the resizeImage function we can do this:

This resizes the image and converts the output to a buffer to return to the user. You can think of a buffer like a big array of ones and zeroes that represent our resized image.

Now we can go ahead and implement the pickRandomFileInDirectory function which picks a random file in a directory and returns the file's name we can implement it like this:

This grabs the names of all the files in a directory and then we pick a random one and return it.

And that's it for the image.ts service!

API Route handling

The route handling is pretty simple we use celebrate to validate the query data in the request. We validate the data x and y as numbers. We first use the pickRandomFileInDirectory function to pick a random file in the art/ directory after that we use resizeImage to resize the image and return the image buffer to the user.

Adding the config

Now you just need to configure a value to use for the size of the image in case it's not defined. Todo this just open up config/index.ts and add something like this in if you want more control over the fault size you can define the x and y defaults separately 

defaultImageSize: 100,


Now you are done! You can open up the demo.html file in the github repo that you cloned to see a quick example of using the API

Using the API is pretty simple in the route handling code we grab the x and y from the URL query params and use those to resize the image so we can pass them like this:

Or because if they are not defined we default to the setting in the config file just like this:

You can even do something like this and only pass one of the size params