Javasript APIs as a Python Developer

·

13 min read

Javasript APIs as a Python Developer

Building a Comprehensive "Store" API: An In-Depth Exploration of Simple Express.js, Fastify, and NestJS APIs

Dear Esteemed Developers,

Embark on an enriching journey into the world of backend development by creating a comprehensive store API using three prominent and robust JavaScript frameworks: Express.js, Fastify, and NestJS. This introductory guide aims to establish a strong foundation for you to expand and refine your expertise in developing reliable, scalable, and efficient APIs.

As a Python developer, my primary focus has been on different technologies. But as my main focus currently is working as a Software Project Manager it has led to a situation in which I am drawn to understand the ins and outs of JavaScript ecosystem too. The contents of this blog post are derived from my personal experiences, notes, and insights as I learn about these technologies and as it is part one of my Learning JavaScript series the same will also apply to further postings. Also due to my experience with Python I am most likely not going to be posting the very simplest things about JavaScript even though I will eventually look thru them but as it is in programming the logic is the same syntax is juts a slang for the logic. Therefore, please exercise discretion and consider these insights as supplementary knowledge, particularly if you are an experienced JavaScript developer.

Preparing Your Development Environment for Success

Installing Node.js and npm - The Essential Tools

To kick off your journey, you'll need to make sure that you have both Node.js and npm (Node Package Manager) installed on your system. These tools are crucial for managing dependencies and running your JavaScript applications. If you haven't installed them yet, head over to the Node.js official website nodejs.org to download the latest versions of Node.js and npm.

Link image to nodejs

Once you've completed the installation process, it's essential to verify that both tools are correctly installed and functioning on your system. To do this, simply open your preferred terminal or command prompt and execute the following commands:

node -v
npm -v

1. Express.js: Quick and Flexible

What is Express.js?

Express.js, often referred to simply as "Express," is a minimalist web application framework for Node.js. It simplifies the process of building web applications and APIs by providing a robust set of features and utilities. For me coming from the Python ecosystem reminds me of Flask. I have a blogpost about these and I will link it at the bottom of this post.

Key Features:

  1. Middleware: Express uses a middleware concept, where functions have access to the request and response objects, and the next middleware function in the application’s request-response cycle. These functions can execute any code, modify request and response objects, end the request-response cycle, or call the next middleware function in the stack.

  2. Routing: Express allows you to define routes based on HTTP methods and URLs, letting you easily handle different types of requests (like GET, POST, PUT, DELETE) to various URL paths.

  3. Template Engines: While Express itself is unopinionated about how you structure your application or which libraries you use, it supports template engines out-of-the-box. This means you can render dynamic content on the server and send HTML pages as responses.

  4. Easy Integration: Express is designed to be flexible. You can integrate it with various databases or set it up as a REST API, GraphQL endpoint, or even a full-fledged MVC application. It also integrates seamlessly with many Node.js middleware and libraries.

  5. Performance: Being minimalist and lightweight, Express ensures that there's minimal overhead, allowing for a performant backend solution.

Why Use Express.js?

  1. Simplicity: Express provides a thin layer of fundamental web application features without obscuring Node.js features. This means you can get an application up and running with very few lines of code.

  2. Flexibility: Express is unopinionated. You have the freedom to choose how you structure your application, which libraries or databases to integrate, and more. This flexibility means Express can be as simple or as complex as you need it to be.

  3. Ecosystem: Express has a vast ecosystem, thanks to the npm registry. There are countless middleware and libraries available that are built specifically for Express, making it easy to add functionalities like authentication, data validation, or any other feature you might need.

  4. Community Support: Being one of the most popular frameworks for Node.js, Express has a vast and active community. This means a wealth of tutorials, guides, and third-party tools are available. Additionally, any issues or questions are often quickly addressed by the community.

image as link to expressjs.com

Setting up Express.js

mkdir express-store
cd express-store
npm init -y
npm install express

Building a Store API with Express.js

const express = require('express');
const app = express();
const PORT = 3000;

// Sample in-memory store
const items = [
    { id: 1, name: 'Laptop', price: 1000 },
    { id: 2, name: 'Phone', price: 500 }
];

// Endpoint to fetch all items
app.get('/items', (req, res) => {
    res.json(items);
});

app.listen(PORT, () => {
    console.log(`Express server running on http://localhost:${PORT}`);
});

Run your server:

node [your-file-name].js

In-Depth Exploration of Express.js: Express.js is widely recognized for its minimalist and efficient approach to web application development. The code snippet provided demonstrates the process of setting up a rudimentary server, defining an array of items, and creating a single route '/items' to retrieve these items.

The code begins by defining a 'store' with a constant variable named 'items', which is an array containing two objects. Each object represents an item with properties such as 'id', 'name', and 'price'. The first item is a laptop priced at $1000, while the second item is a phone priced at $500.

Next, the code establishes an endpoint for fetching all items using the 'app.get()' method. This method takes two arguments: the route ('/items') and a callback function with 'req' (request) and 'res' (response) parameters. The callback function is responsible for handling the incoming request and sending the appropriate response.

Within the callback function, the 'res.json(items)' line is used to send the 'items' array as a JSON response. This line of code effectively converts the 'items' array into a JSON-formatted string and sets the 'Content-Type' header to 'application/json'. As a result, when a client sends a request to the '/items' endpoint, the server will respond with the JSON representation of the 'items' array.

Finally, the 'app.listen()' method is called to start the Express server on a specified port. The 'PORT' variable represents the port number on which the server will listen for incoming requests. The second argument of the 'app.listen()' method is a callback function that logs a message to the console, indicating that the Express server is up and running on the specified URL.

This command will start the server, and you can then access the '/items' endpoint through a web browser or API client to fetch the items as a JSON response.

2. Fastify: Built for Speed

What is Fastify.js?

Fastify is a web framework highly focused on providing the best developer experience with the least overhead and a powerful plugin architecture. It is inspired by Hapi and Express and, as the name suggests, is designed to be one of the fastest web frameworks for Node.js. Again for me the development style was similarlish as it is with FastApi.

Key Features:

  1. Performance: One of the standout features of Fastify is its performance. It has been built from the ground up to be one of the fastest web frameworks for Node.js, with benchmarks to back up this claim.

  2. Schema-based: Fastify uses JSON Schema to validate routes and serialize outputs. This not only improves performance but also provides better developer tools and supports generating documentation automatically.

  3. Plugin System: Fastify's powerful plugin system allows you to extend its functionalities. Plugins can be easily shared among applications and can encapsulate routes, dependencies, and hooks.

  4. Lifecycle & Hooks: Fastify provides a lifecycle for requests and a variety of hooks that give you control over request and response, allowing for functionalities like modifying request/response or adding authentication layers.

  5. Logging: Integrated with Pino, a very fast logger, Fastify provides an extensive logging utility out-of-the-box.

Why Use Fastify.js?

  1. Speed: As the name suggests, Fastify is designed for speed, both in terms of developer experience and runtime performance.

  2. Validation and Serialization: The use of JSON Schema to validate and serialize data can lead to safer and more optimized applications.

  3. Fully TypeScript Ready: Fastify's internal codebase is written in TypeScript, making it a good choice for developers who prefer strong typing.

  4. Extendable: With its plugin architecture, you can extend Fastify or even integrate other utilities and libraries with ease.

  5. Community and Ecosystem: Fastify has an active community and a growing ecosystem. There are numerous plugins available, and community support is robust, ensuring longevity and reliability.

Setting up Fastify

mkdir fastify-store
cd fastify-store
npm init -y
npm install fastify

Building a Store API with Fastify

const fastify = require('fastify')({ logger: true });
const PORT = 3001;

const items = [
    { id: 1, name: 'Laptop', price: 1000 },
    { id: 2, name: 'Phone', price: 500 }
];

fastify.get('/items', async (request, reply) => {
    return items;
});

fastify.listen({ port: PORT, host: '127.0.0.1' }, (err, address) => {
    if (err) {
        fastify.log.error(err);
        process.exit(1);
    }
    fastify.log.info(`Fastify server running on ${address}`);
});

In-Depth Exploration of Fastify: Fastify is a highly efficient web framework for Node.js, boasting exceptional performance and minimal overhead. This is achieved through its well-designed architecture and the way it internally manages routes, which ultimately positions it as one of the fastest web frameworks available for Node.js developers.

One of the key features of Fastify is its built-in logging capability, which can be enabled by setting the 'logger' option to 'true'. This feature proves to be incredibly useful during the development process, as it provides developers with detailed logs that can help them identify issues, track progress, and optimize their applications more effectively.

Furthermore, Fastify's streamlined approach to handling HTTP requests and responses allows it to maintain a high level of performance, even as the complexity of the application increases. This makes it an ideal choice for developers who are looking to build scalable and high-performing web applications using Node.js.

In the given code snippet, Fastify is used to create a simple server that listens on a specified port and host. The server has a single route, '/items', which returns a list of items when accessed. The server is set up to listen on the local IP address '127.0.0.1' and the specified port number. If an error occurs during the server startup, Fastify's logging feature will output the error details, allowing developers to quickly identify and resolve the issue. Once the server is up and running, Fastify logs an informational message indicating the server's address, making it easy for developers to access and test their application.

3. Building an API with NestJS

NestJS, a progressive Node.js framework, is widely lauded for its modularity and use of decorators. It's built on top of TypeScript and offers a more structured way to build backend applications compared to Express or Fastify. For me, this was a new tech to dive into and in the end, reminded me a lot about Django with a lot of batteries included stuff coming in with the package. This is something I need to look into more. My VSCode was also totally messed up with the prettier configs that came along so need to look into that too but those did not mess up running it.

What is NestJS?

NestJS is a progressive Node.js framework built on top of TypeScript for building efficient, reliable, and scalable server-side applications. NestJS combines elements of Object-Oriented Programming (OOP), Functional Programming (FP), and Functional Reactive Programming (FRP) and offers a comprehensive development kit for building enterprise-level applications.

Key Features:

  1. Modularity: NestJS is built around the strong modular architecture using modules, which makes it easy to organize features and functionality and promote code reusability.

  2. Decorators: Leveraging TypeScript, NestJS uses decorators for many tasks, reducing boilerplate and simplifying various processes, from defining routes to injecting dependencies.

  3. Dependency Injection: Inspired by Angular, NestJS comes with a powerful Dependency Injection (DI) system out-of-the-box. It makes it easier to manage and test your applications.

  4. Extensible: NestJS is very extensible and allows developers to use other libraries thanks to its modular nature.

  5. Built-in CLI: The NestJS CLI is a powerful tool that boosts productivity, allowing developers to generate, build, and manage NestJS applications with ease.

  6. First-class TypeScript Support: While NestJS supports both TypeScript and JavaScript, its primary language is TypeScript, offering strong typing and modern language features.

Why Use NestJS?

  1. Structured Approach: NestJS offers a layered architecture that ensures a separation of concerns and promotes code modularity.

  2. Flexibility: While NestJS provides a structure, it remains flexible, allowing developers to integrate any package or library they need.

  3. Comprehensive Documentation: NestJS boasts a well-maintained documentation that covers everything from the basics to advanced topics, making it easier for developers to get started and master the framework.

  4. Active Community: An active and growing community means better support, more third-party tools, and a brighter future for the framework.

  5. Enterprise-Ready: With its set of tools, NestJS is well-suited for building large-scale, maintainable, and scalable applications.

    Click the image below to visit NejstJs

Image of NestJs site and link to it

Setting up NestJS

  1. Install NestJS CLI: To scaffold and manage NestJS applications, you'll need the NestJS CLI. Install it globally using npm:
npm install -g @nestjs/cli
  1. Create a New NestJS Project:
nest new nestjs-store

This command will create a new directory named nestjs-store and set up a new NestJS project inside it.

  1. Navigate to the Project Directory: This is crucial. Ensure you are inside the project directory before proceeding with other commands:
cd nestjs-store

Building a Simple API Endpoint

For our example, let's create an API that returns a list of items from a "store".

  1. Open the Main Controller: By default, NestJS generates an app.controller.ts file in the src directory.

  2. Modify the Controller: Replace the content of app.controller.ts with the following:

import { Controller, Get } from '@nestjs/common';

@Controller('items')
export class AppController {
    private readonly items = [
        { id: 1, name: 'Laptop', price: 1000 },
        { id: 2, name: 'Phone', price: 500 }
    ];

    @Get()
    getItems(): any[] {
        return this.items;
    }
}

Here's a breakdown:

  • @Controller('items'): This decorator indicates that our routes in this controller will be prefixed with items.

  • @Get(): This decorator maps the following method to HTTP GET requests.

  • getItems(): This method returns the list of items when accessed.

  1. Start the NestJS Server:
npm run start

Once the server is running, you can access the list of items by navigating to http://localhost:3000/items in your browser. You should see the items array as a JSON response.

Wrapping Up

NestJS provides a structured and modular approach to building backend applications, making it a great choice for larger projects or those who prefer a more organized codebase. As with any framework, there's a learning curve, especially if you're transitioning from a more minimalist framework like Express or Fastify. However, the benefits of using NestJS, such as its strong typing, modularity, and use of decorators, can greatly enhance the developer experience and the maintainability of the code. Like mentioned reminds me of Django but then again the entire JavaScript Ecosystem is new to me so everything feels like a shiny object and a fun adventure.


Conclusion

In conclusion, Express.js, Fastify, and NestJS are powerful JavaScript frameworks that each offer unique advantages for building store APIs. Express.js is known for its simplicity and flexibility, Fastify boasts exceptional performance, and NestJS provides a structured and modular approach. By exploring these frameworks, developers can enhance their backend development skills and create robust, scalable, and efficient APIs.

Please comment or contact me on X / Twitter if you are interested in these topics and I am more than happy to write about them more in the future.

Simple Python APIs
This article GitHub for JavaScript APIs

Did you find this article valuable?

Support Timo by becoming a sponsor. Any amount is appreciated!