DEV Community

Cover image for API (Application programming interface)Design in Node.Js
reach2arunraj
reach2arunraj

Posted on • Updated on

API (Application programming interface)Design in Node.Js

API:

· A server that creates an HTTP interface for interacting with some data

· Usually, a sever on some remote machine that dictates how another application ca interact with some data

· Basic Data operation such as Create, Read, Update, Destroy(CRUD)

REST:

· An API design that combines DB resource, route paths, and HTTP verbs to allow application describe what action is trying to perform.

· Popularized when SaaS products starting offering API for integrations.

· Works with basic data Models.

· Hard to scale with complex data models and client requirements.

Node Js and API:

· Node Js is JavaScript, it’s async and event-driven.

· Single-threaded (can optimize)

· When kept async, Node can handle a high amount of concurrent requests.

· Not great for CPU intensive work (data crunching, ML, Big math)

· So many open-source tools to help build API’s

EXPRESS:

· Handles all the tedious tasks like managing sockets, route matching, error handling, and more.

· Open Source

· Has a Huge community and support from anything that has to do with API’s in NodeJS

MongoDB:

· Non-relational document store that is easy to get started and scale well.

· Open Source and backend by a big company.

· Tons of hosting Solution.

· ORM(object-relational mapper)/ODM(object data mapper) and other libs are some of the best for any DB, how to interact with models.

MIDDLEWARE:

· List of functions that executes, in order, before your controllers.

· Allow you to execute functions on an incoming request with guaranteed order, to transform the request when it comes in.

· Great for Authentication, transforming the request, tracking, error handling.

· Middleware can also respond to request as a controller would, but that is not their intent.

  1. app.use(cors()) — Cross-origin resource sharing (Two different domains share the same API).

2.
app.use(json()) — (req.body) -> get all these bytes and put them together, turn into String and parse them.

3.
app.use(urlencoded()) — transform the request and attach parameters to the URL like Query string(?).

4.
app.use(morgan()) — logs server data.

REST routes with Express:

· Express has a robust route matching system that allows for exact[“/data”], regex[“^(me)”], glob[“/users/*”], and parameter matching[“/:id”]

· It also supports HTTP verbs on a route-based level. Together with the routing, you can create REST API’s

· Routes match in the order that they were defined (top to bottom)

· For Abstraction, Express allows you to create sub-routes that combine to make a full router

Data Modeling:

· You Should always use a Schema for models, and mongoose makes it easy.

· MongoDB is a Schemaless document store, but you should always use schemas if you don’t want to go crazy

· MongoDB has added support creating schemas, but Mongoose is much better

· We can create models for each REST resource we want to expose via the API.

Schemas to models:

· Schemas hold the instructions for the models. Things like validation, names, indexes.

Controllers & Routes:

· Controllers are just a middleware but with the intent on returning some data.

· Controllers handle what a Route + Verb combo can access from the DB.

· Final middleware in the stack for a request. There is no intent to proceed to another middleware function after a controller.

· Controllers implement the logic that interacts with our DB models.

· Can generalize controllers to work for many models because we’re going with a REST approach which requires CRUD action on a resource.

Using Models:

C — model.create(), new model()

R — model.find(), model.findOne(), model.findById()

U — model.update(), model.findByIdAndUpdate(), model.findOneAndUpdate()

D — model.remove(), model.findByIdAndUpdate(), model.findOneAndRemove()

Auth:

· You can never truly protect an API, but requiring authentication makes it a bit safer

· Authentication is controlling if an incoming request can proceed or not

· Authorization is controlling if an authenticated request has the correct permission to access a resource.

· Identification is determined by who the requester is.

JWT Authentication:

· Token passed every request to check auth on the server. It is stateless.

· A token strategy that allows the API to be stateless with user auth.

· Created by a combination of secret on the API and a payload like a user object.

· Must be sent with every request where the API will then try to verify the token was created with the expected secrets.

· After successful verification, the JWT payload is accessible to the server. Can be used to authorization and identification.

Discussion (0)