can i use one backend request for couple endpoints? - node.js

http://localhost:4200/product-list?gender=2&category=4
http://localhost:4200/product-list?gender=2
http://localhost:4200/product-list?category=4
i want to use one backend controller for the endpoints.
can i do that? i tried but with no success. (using angular)

What exactly did you try with angular? The backend controller? Angular is a frontend framework.
However, you could indeed have one single controller (e.g. ProductController) for your endpoints. I would suggest implementing a "getProducts" method that can be filterable. That way you can use single endpoint and provide optional filter options as needed.

I may not understand your question entirely, so please stat otherwise. But, Yes. You have one endpoint stated above, with different query params. Depending on the different query params (their value or even if they are present), your singular endpoint can do something different.
So your endpoint is
http://localhost:4200/product-list
This endpoint (which there is only one), can have as many query params as you like. As per the response above, Angular does not handle this, this would be some backend functionality for your end point, to read the request, and based on what query params are 'found' then trigger a different response.

Related

Is it bad practice to include id of object i want to delete in url query?

Im wondering if its bad idea for me to send DELETE Request on server endpoint
lectures/remove?id=${lecture._id}
I am aware that DELETE Requests shouldn't include req.body.
Does it matter if i pass information via params or query? or is there perhaps better way to sending info as delete request in order to delete some info from db?
Feels like just matter of semantics.
Thanks for answers in advance.
In general, if you have a RESTful API, and you want to refer to a resource you use URL parameters as you want to identify that single resource.
So you would have something like
DELETE /lectures/:lectureId
As it's a single resource of lectures.
However, you may want to delete multiple resources and in that case, it is a common practice to use query parameters
DELETE lectures?id=LECTURE_1&id=LECTURE_2&id=LECTURE_3...
So the "best practice" that you might be missing here is that you should use nouns instead of verbs in endpoints as you are dealing with resources:
Keep URLs verb-free
Avoid actions — think about resources
Unless you design your API in a way that you trigger a deletion task/process by calling this endpoint then you can challenge this recommendations.
See more:
http://opensource.zalando.com/restful-api-guidelines/#delete
RESTful - What should a DELETE response body contain
https://stackoverflow.blog/2020/03/02/best-practices-for-rest-api-design/
https://learn.microsoft.com/en-us/azure/architecture/best-practices/api-design

What is the difference (if any) between a route and an endpoint in the context of a RESTful API?

Question
I have a probably rather simple question, but I'm unable to find an answer with nice explanations:
What is the difference (if any) between a route and an endpoint in the context of a RESTful API developed within a Node.js / Express application (but these concepts may be broader?!)?
(Does it relate to URLs in some way?)
Example
For example, in this article: https://medium.com/#purposenigeria/build-a-restful-api-with-node-js-and-express-js-d7e59c7a3dfb we can read:
We imported express which we installed at the beginning of the course, app.get makes a get request to the server with the route/endpoint provided as the first parameter, the endpoint is meant to return all the todos in the database.
These concepts are used interchangeably, which makes me confused.
(please note that I'm a 100% beginner with REST API, nodejs and express but I try to do my best to learn).
Edit
The two first answers chronologically speaking make me even more confused as they are perfectly antagonistic.
3 different concepts here:
Resource: {id: 42, type: employee, company: 5}
Route: localhost:8080/employees/42
Endpoint: GET localhost:8080/employees/42
You can have different endpoints for the same route, such as DELETE localhost:8080/employees/42. So endpoints are basically actions.
Also you can access the same resource by different routes such as localhost:8080/companies/5/employees/42. So a route is a way to locate a resource.
Read more: Endpoint vs. route
Read more: Endpoint vs. resource
Route
URI path used to access the available endpoints.
example: http://www.mywebsite.com/
Endpoint
performs a specific action.
has one or more parameter(s).
returns back data.
example: GET http://www.mywebsite.com/Products
A Route is the URI, and the Endpoint is the action performed on the URI.
Routes and endpoints are associated concepts - you can't really have one without the other.
What is an endpoint?
Generally speaking, an "endpoint" is one end of a communication channel where one system interacts with another system. This term is also used similarly in networking.
For a typical web API, endpoints are URLs, and they are described in the API's documentation so programmers know how to use/consume them. For example, a particular web API may have this endpoint:
GET https://my-api.com/Library/Books
This would return a list of all books in the library.
What is a route?
A "route" is typically code that matches incoming request paths to resources. In other words, it defines the URL and what code will be executed. A route path might contain regular expressions, patterns, parameters, and involve validation. For example, consider this route path:
"{controller}/{action}/{id?}"
In ASP.NET, pattern matching is applied, so GET https://my-api.com/Library/Books/341 would call the Books public method on the Library class, passing a parameter of 341. Routing frameworks can be very flexible and versatile.
The simplest example of an endpoint is to put a file you want to be consumed (say data.json) inside the public_html folder of your web server. It can be reached by GET https://my-api.com/data.json. The routing is handled by the web server out of the box and no routing code is required.
Some good things to read next:
Express.js - Routing
Wordpress Developer Resources - Routes and Endpoints
When to use "client-side routing" or "server-side routing"?
Endpoints are basically use to perform specific task and return data and endpoints are kind of part of a route.
For example is route and this is also a route but here both of them are returning different data not he same so, we can say that the last two parameter here is kind of end point means the id and question string.
endpoints:
/56075017/difference-between-route-and-endpoint
/56040846/how-to-use-the-classweight-option-of-model-fit-in-tensorflow-js
route:
https://stackoverflow.com/questions/56075017/difference-between-route-and-endpoint
https://stackoverflow.com/questions/56040846/how-to-use-the-classweight-option-of-model-fit-in-tensorflow-js
In this example: http://example.com/my-website/comments/123:
Route:
my-website/comments/123
Endpoints: (a fancy word for a URL with an action)
GET http://example.com/my-website/comments/123. returns the comment data.
DELETE http://example.com/my-website/comments/123. deletes the comment and returns the now-deleted comment data.

Extending existing RESTful API using Node.js

I am currently running a web service on an Apache Tomcat servlet container. The web service has a base URL and exposes my applications data using the following structure:
http://[hostname]:[port]/path/to/root/[db_table_name]/[primary_key]?fields=name,...
An HTTP GET call to a URL like the one above would return a JSON formatted string.
Though the documentation for my application describes this as a RESTful API, I am confused because I was under the impression that true RESTful APIs do not use query strings. Rather, as I understand it, a true restful API provides a uniform structure, in the form of resource endpoints.
My questions relate to how I can create a custom API to leverage the existing API using Node.js. I do not want to rewrite the application logic or database calls; I just need to know how I can create the API calls using Node.js (possibly using Express or some other framework) and let the existing API handle the request.
For example, I could write Node.js code using the Express module that has several routes, these routes would handle client requests that in turn would call the existing API (i.e. /path/to/root/[table_name]/[pk]... and return the response.
If my Apache Tomcat server is listening on port 8080, how would I deploy my Node.js server to listen on another port and then redirect requests to the existing WS URL on port 8080.
Does the Express framework support explicitly specifying a root path (such as http://localhost:3000/path/to/root/[table_name]/[pk]) as the default root path?
Finally, I know REST APIs support CRUD operations. In the case of a POST method, does Express (or Node.js) have built-in logic to handle duplicate POST requests so that duplicate records don't get created in the database.
I'm reading through different article and tutorials on REST but I think I'm missing something. Any information or advice that can take me in the right direction would be much appreciated.
there's a lot to cover here but I'll try to cover your three questions. Since you have mentioned using Express I will answer assuming that Express is the framework you are using.
If you are using Express, you can choose which port to listen to when you start the server, so you can choose any port that you like at that point (see here).
If you need to redirect a request you can do so easily with res.redirect() (see here). However, you could also call the other web service directly, retrieve the data and return it to the client instead of redirecting them if you prefer. That would require some more code to make the http requests in node.js though.
I am not 100% sure if this is the answer to your question, but there are ways to add a "base path" or namespace to all of your routes. I found this example where various namespaces are used but in your case you only need one which applies to all routes.
I don't think there is a built-in way to do this. The best I can think of is potentially creating some kind of ID for the request so that if it is sent twice you could use this to check but it's far from ideal.
I would like to add that I'm not sure where the idea that query parameters not being RESTful comes from? I think query parameters are fine because that is how you query! Otherwise you couldn't ask for the right data from your RESTful API. Let's say you have a /posts endpoint and you want to get the posts of a particular user (user ID = 1). The RESTful way to do this would be to issue a GET request to /posts?user=1.
Hope this helps!

Rest API on express. Parameter passing

Folks,
I need your expert advice:
I have two endpoints on my node server using express:
'/api/status/:id'
'/api/status/all'
Now both have different purpose. One returns one status by Id and other one is all statuses. But express seems to be taking both request as the first one hence it is breaking on cast error.
any help please.
You can define '/api/status/all' before '/api/status/:id' and if request will match to all it will be handled with that middleware.

How can Socket.io and RESTFul work together?

(I'm not familiar to RESTFul, please correct me if my concept is wrong)
In RESTFul architecture, we map every action to an URL. If I click "post a article", may it's actually URL http://example.com/ and some data action=post&content=blahblah.
If I want to post, but not refresh the whole web page, I can use javascript's XMLHTTPRequest. I post it and then get it's content and insert it to a div in my page. These action is all asynchronous.
Then I know there is something named WebSocket and it's wrapper socket.io. It use "message" to communicate between client and server. When I click "post" the client just call socket.send(data) and wait for server's client.send(data). It's magical. But how about URL?
It's possible to use the two model both without repeating myself? In other word, every action has it's URL, and some of them can interact with user real-timely(by socket.io?)
Moreover, should I do this? In a very interactive web program(ex. games), the RESTFul is still meaningful?
You're defining a handler for actions that map to REST over http. POST and GET generally refer to update and query over an entity. There's absolutely no reason you can't just define a handler for generic versions of these CRUD operations that can be used in both contexts. The way I generally do this is by introducing the concept of a 'route' to the real-time transport, and mapping those back to the same CRUD handlers.
You have a session, you can impose the same ACL, etc.
 +---------------------------------+
 |                                 |
 |      BROWSER                    |
 |                                 |
 +--+--^-------------------+---^---+
    |  |                   |   |
    |  |                   |   |
 +--v--+---+            +--v---+---+
 |         |            |          |
 | HTTP    |            | SOCKET.IO|
 +--+---^--+            +--+---^---+
    |   |                  |   |
 +--v---+------------------v---+---+
 |                                 |
 |        ROUTING/PUBSUB           |
 +-+--^-------+--^-------+--^------+
   |  |       |  |       |  |
 +-v--+--+  +-v--+--+  +-v--+-+
 |       |  |       |  |      |
 | USERS |  | ITEMS |  |ETC   |
 +-------+  +-------+  +------+
     ENTITY CRUD HANDLERS
I posted this on my blog recently:
Designing a CRUD API for WebSockets
When building Weld, we are using both REST and WebSockets (Socket.io). Three observations on WebSockets:
Since WebSockets are so free-form, you can name events how you want but it will eventually be impossible to debug.
WebSockets don’t have the request/response form of HTTP so sometimes it can be difficult to tell where an event is coming from, or going to.
It would be nice if the WebSockets could fit into the existing MVC structure in the app, preferably using the same controllers as the REST API.
My solution:
I have two routing files on my server: routes-rest.js and routes-sockets.js
My events look like this example: "AppServer/user/create".
I use forward slashes (“/”) to make the events look like routing paths.
The first string is the target (~”host name” if this actually was a path).
The second string is the model.
The third string is the CRUD verb: i.e. create, read, update, delete.

Resources