Creating an Express API Step-by-step

Todd H. Albert, Ph.D.
Boca Code
Published in
3 min readJul 15, 2021

As someone that teaches Node and Express, I know few people that create APIs from scratch as often as I do. So for me, it has become second-nature — I can literally write every line of code from memory.

But for most, this is a task that isn’t completed as often. So here is a quick step-by-step guide to setting up a basic Express API. (I’ll follow up with a second article on doing this in a super-scalable, serverless environment.)

  1. Create a new folder for your API.
mkdir new-api

2. Change to that new folder.

cd new-api

3. Initialize this new folder as a project with NPM.

npm init -y

4. Install Express.js.

npm i express

5. Create a “.gitignore” file and add “node_modules” so you don’t needlessly track these thousands of files.

5. Create an “index.js” file, import Express, initialize a new Express app (called “app” by convention), then listen on a port (here 3000 if there isn’t a different port defined in your environment).

6. Now you can set up your first route. Let’s use a GET (http) method on route ‘/test’.

7. Create a function (takes arguments “request” and “response”, often shortened to “req” and “res”) to handle this request and return something using the .send() method to the “response” (or “res”, as below). We put this function in /src/test.js.

8. Import this function in our index.js.

9. Now we can test this API point by running “node .” inside this folder and then going to http://localhost:3000/test in a browser (browsers make GET requests by default).

--

--

Todd H. Albert, Ph.D.
Boca Code

Software engineer; been mentoring founders, engineers, and students for 22+ years and building dozens of projects for startups to Fortune 100 companies.