How to Create a NodeJS API Without Using a Framework
Node.js is an open-source JavaScript runtime built on chrome’s v8 engine that allows you to run JavaScript code outside a browser.
Its event model, ecosystem, and speed have made Node.js one of the most wanted and used runtimes for server-side applications.

Most Node.js API servers use Express or another framework. However, you could also create a simple Node.js API without a framework in just a few steps.
Step 1: Setting Up Your Development Environment
Create a project directory andcdinto it by running:
Next, initializenpmin your project by running:

This CRUD API will feature the use of MongoDB, a NoSQL database, and its popular ODM, mongoose.
Run the following command to installmongoose:

Next, create aserver.jsfile in your project’s root directory and add the code block below to create a server:
This code block imports the http module, a core Node.js module. The http module allows Node.js to transfer data over HTTP. This module contains the methods required to create a server.

Next, it calls the http module’screateServermethod which creates and returns an instance of a server. ThecreateServermethod takes a callback function with a request and response object as parameters.
Next, the code calls thelistenmethod on the returned server instance. This allows the server to start listening for traffic on the given port. Thelistenmethod fires a callback—the second argument—when it succeeds.

Finally, create two directories namedroutesandmodelsin your project’s root directory. Theroutesfolder will contain the routing logic for your API, whilemodelwill contain everything related to the database.
Step 2: Connecting Your Application to a Database
Inserver.js, importmongoose:
Call theconnectmethod onmongooseand pass your MongoDB URI as an argument:
Step 3: Creating an API Model
Create a CRUD API for a simple blog application. In yourmodelsfolder, create ablogModel.jsfile and add the following code to your file:
The code block above creates a mongoose model with two properties and maps them to a MongoDB database.
Both properties in this model have aStringtype withrequiredset totrue. The accompanying error messages will display if a request body does not contain either of the properties.
The final line creates and exports a mongoose model by calling themodelmethod onmongoose.Pass the model name (Blog) as the first argument and a schema (blogSchema) as the second argument.
Step 4: Implementing Routing in Your Application
Without the aid offrameworks like Express, you’ll have to manually create the logic to handle each request made to your API.
First, create ablogRoutes.jsfile in yourroutesfolder, then import the blog model:
Next, create an asynchronousrouterfunction, passreqandresas parameters, and export the function:
This function will contain all your routing logic.
Next, you’ll implement the routing logic route by route.
GET Routes
Add the code block below to yourrouterfunction to implement theGETroute handler for requests made to/api/blogs:
The code block above checks theurlandmethodproperties of the request object. It then fetches all blogs from the database via thefindmethod on the mongoose model (Blog).
Next, it calls thewriteHeadmethod onres, the response object. This method sends a response header given three arguments: a status code, an optional status message, and headers. The200status code represents a successful response and the content-type for this API call is set toapplication/json.
Finally, close the request to ensure the server doesn’t hang by calling theendmethod onres. The call toJSON.stringifyconverts theblogsobject to a JSON string and passing that to theendmethod returns it as the response body.
Add the code block below to yourrouterfunction to implement theGETroute handler for a single resource:
This code uses thematchmethod, which takes in a regex expression as an argument, to check if the url matches the format:/api/blogs/.
Next, extract theidproperty from theurlstring by calling itssplitmethod. This method takes a pattern as an argument (/), splits the string based on the pattern, and returns an array. The third element of that array is theid.
Finally, retrieve the document with the matchingidfrom your database. If it exists, send aresponse code of 200, close the request, and send the retrieved blog. If it doesn’t exist, throw an error and send it as a response in the catch block.
POST Route
Add the code block below to your router function to implement thePOSTroute handler:
The request object implements theNode.js ReadableStreaminterface. This stream emits adataand anendevent which give you access to data from the request body.
This code listens for the data event and handles it by converting it to a string and concatenating it to thebodyvariable. In theendevent handler, it creates aBloginstance with the parsed body string. It then saves the new blog, sends the status code and content header, and closes the request.
Add the code block below to your router function to implement thePUTroute handler:
The PUT request handler is almost identical to thePOSTrequest handler, except that it extracts theidproperty from theurlto update the relevant blog.
DELETE Route
Add the code block below to your router function to implement yourDELETEroute handler:
This code block extracts theidfrom theurl, deletes the document with the matchingid, sends the status code and headers, and closes the request.
Finally, importrouterin yourserver.jsfile and call yourrouterfunction, passingreqandresas arguments:
This allows your server to intercept and handle requests appropriately.
You can find the completed project in thisGitHub repository.
Using a Node.js Framework
Even though it’s possible to create a web API by hand, it can be a difficult task. You’ll need to make sure you’ve covered lots of edge cases and your code had better be bug-free.
Over the years, developers have built frameworks like ExpressJS, NestJS, Fastify, etc., to make it much easier.
User authentication is crucial for protecting sensitive information. Luckily, it’s not difficult to implement this.
Make sure you don’t miss these movies and shows before Netflix removes them.
Now, I actually finish the books I start.
Unlock a world of entertainment possibilities with this clever TV hack.
This small feature makes a massive difference.
You’re not getting the most out of what you pay for iCloud+.