Categories
API with Node.js Node.js

Example backend API in Node.js – Video Tutorial

In this video-tutorial, my goal is to create an example Node.js backend API which can be used for React / Next.js projects. API will return a JSON response.

The thing is most of the parts of React / Next.js projects require working backend API so you can fetch data. It’s relatively easy to do so in Python or Golang. Usually with a few lines of code. In this coding session, I want to explore for myself if it is the same in Node.js.

Since it is a coding session and a video-post at the same time, on this page I will post the process, which might contain a lot of “progress content.” If you want to see the result and just a short explanation, jump to the end of the page.

Part 1: Build a JSON API in Node.js

If you want to jump directly to the coding part start at 1:25.

In part 1, we create a very simple Node.js app with the following features:

  • Execute as a webserver to serve a backend API.
  • Return an example JSON response.
  • Receive header and method information from the incoming request.

Here we use pure Node.js implementation:

JSON API in Node.js

Part 2: Introduce package.json and use nodemon

For the “Hello, world!” project not having package.json is OK. However, before we advance our simple project, we need to introduce the package.json file:

  • Contains the project’s metadata (name, version, etc.).
  • Repository information, author, license.
  • Information about project dependencies.
  • Entry point (index.js, app.js, or something else).
  • Executable command scripts.
  • And many more.

I also recommend using nodemon. It is a tool that will monitor your source code and refresh the working application. Check the video above for the live-example.

In conclusion, the final code for Part 1 and Part 2 can be found here:

Part 3: Convert pure Node.js API to Express.js Web Server

In this section, we start using Express.js – one of the most popular web frameworks for Node.js.

Here is the source code of the same web application but now with Express.js:

Simple JSON API using Node.js and Express.js

Part 4: Accept URL params and return JSON object by using Express.js features

Topics covered:

  1. Return a JSON response by using res.json() method. This method implicitly uses JSON.stringify() and sets the correct content-type.
  2. Add one more route and accept request params by using the req.params object.

The final version of the updated server.js file:

Express.js: res.json() and accept URL params

Additional Resources

Besides the links mentioned above, these following resources were very helpful to start learning:

Video Tutorial & Live Code: This post has a corresponding Interactive Tutorial where you can watch videos and practice code simultaneously. Check it here.

Follow for Updates

Processing…
Success! You're on the list.

By Kanan Rahimov

Sr. Software Engineer

Leave a Reply