Nested End points with angular resource and server nodejs - node.js

I have a resource /cars and the endpoint in angular defined as
$resource('/cars/:carsId');
to GET all cars and a specific car.
At the server level, I have also added a middle-ware to check that carsId is always a valid MongoID.
Now I want to define another endpoint to GET all redcars.
My initial though was to add another resource like
$resource('/cars/redcars');
but this does not work since at the server level, my middle-ware will through an error because redcars is not valid MongoID.
My question is what is the best approach in this case ?
I can add a logic at server to check if the MongoID is invalid, but, if the value is redcars then return all redcars.
or there is a better way of doing this.
Thanks
pkpk

Typical patterns are:
use query parameters, as in, /cars/search?color=red
use /cars/types where the /cars/types/:color can be applied
An excellent resource for design patterns in API design is the Apigee API guide. NOTE: I am not endorsing Apigee by recommending their guide; I simply find that this ebook has many useful patterns collected in one place.

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

Correct way to implement a REST API using MVC

Summary
I am seeing a lot of contradictory architectural examples of a REST API in my work and keep getting different opinions on the subject.
I am familiar with the principles of REST and seeing as each endpoint points to a resource followed by a verb such as /project/create project/123/read.
Following the MVC pattern assuming I have a controller that is responsible for updating a project resource:
router.put("/project/:id/update", ProjectController.put)
First question:
Should this route be responsible for all updates to this resource, in example, assuming different features on my client like marking a project as finished or changing it's title are separated and might not have anything in common for the user. Ending up with the route described above, or should there be something like this:
router.put("/project/:id/mark-as-done", ProjectController.markAsDone)
router.put("/project/:id/update-info", ProjectController.updateInfo)
Second question:
Assuming I want to create a notification resource if a project is created/updated/deleted. Since the notification is a resource on it's own I am not sure how to go about this, but what I assumed and was taught is to use another callback:
router.put("/project/:id/update", ProjectController.put, NotificationController.create)
Third question:
Could I use the same controller to read all resources or just one, for example:
router.get("/project/read", ProjectController.get)
router.get("/project/:id/read", ProjectController.get)
Making the logic in the controller method determinate if it will return all projects or just one. Or should it be separated into different methods?
I would define APIs like this:-
CRUD for Project entity
create- router.post(/projects)
update:- router.put(/projects/:id)
delete:- router.delete(/projects/:id)
read:- router.get(/projects) and/or router.get(/projects/:id)
You can define all above routes in ProjectController.
Regarding Notification entity you can define as follows
read:- router.get(/projects/:id/notifications)
The same can be applied to PUT, DELETE, POST
Here is a good article defining rest guidelines https://stackoverflow.blog/2020/03/02/best-practices-for-rest-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.

Web application (API and Front-end) - routes design

I suppose this type of topics always exist, but i like to have an specifics opinion for my case.
Since 1/2 month i'm thinking about make a listing web application for my daily life (shopping, due, etc.)
I started out define my object model like this (very simple design model)
Models image
So, i decid to create a NodeJS API for back-end, and Angular 7 for front-end. It's not a technical problem for me to develop the application and the API, but my problem is in the design of this, and particuly to the routes design.
My first suggestion for routes API is :
User :
/users
/users/:id
List :
/lists
/lists/:id
Element :
/elements
/elements/:id
Technicaly it's ok, but i'm not sure it's the good practices.
As User contains List and List contains Element, Wouldn't it be better to have routes like this :
/users/:id
/users/:id/list
/users/:id/list/:id
/users/:id/list/:id/element
/users/:id/list/:id/element/:id
Thanks for your answers, or suggestions !
PS : If you have any web sites / video / topics ... to suggests, do not hesitate.
I'd say you got it OK in the first place, the second approach is messy as you can get huge routes, and you're sending a lot unnecesary data. Why do you need the user id to get an element? An element is an entity by itself, and it will probably grow, you may need to get related elements, filter them... its better to just have /elements
What you can do is find simple relations, like:
/users/:id/lists
/lists/:id/elements
I'd recommend reading building apis you won't hate :)
Firstly you are in absolute correct path of defining Routes in angular, at the same time you have to use Lazy loading concept of Routing.
I would recommend you to, go for plural sight course , by Deborah Kurata. I'm not trying to promote or advertise anything but for your current situation that course would be the right guidance. It would provide you all the necessary things that you need to build enterprise ready apps.
Alternatively Core UI Angular provides some best designs which are already implemented with Angular Route and things. Lazy loading and other Angular routing are implemented, all you need to do is understand it.
Hope this helps.,
Principle
as short as possible
easy to read
user-friendly input when the user enters the URL
Examples
User list
/users
User detail
/user/:id
Add user
/user/new
User's functional page
/user/:id/tel

Is there a way to link a specific method to a Route in ServiceStack?

The Problem
I'm aware of the basic way to create a route/endpoint in ServiceStack using methods with names like "Get", "Post", "Any", etc inside a service but in the particular case that I'm trying to work with I have an existing service (which I can make an IService via inheritance) that can not be retrofitted w/ServiceStack attributes and currently uses DTOs for the requests and responses.
This service contains many functions that I do not want to manually mask (as this is a pass-through layer) but otherwise already conform to ServiceStack's requirements. What I'm wondering is if there's a way to manually create these routes in a way that would work like I've mocked up here. My existing functions and DTOs already contain the information I would need to define the routes so if this approach is possible it would only require me to enumerate them at initialization time as opposed to generating the services layer manually.
I noticed there is an extension method on Routes.Add that takes an Expression of type Expression> but I was not able to get that working because I believe the underlying code makes assumptions about the type of Expression generated (LambdaExpression vs MemberExpression or something like that). I also may be barking up the wrong tree if that's not the intended purpose of that function but I can not find documentation anywhere on how that variant is supposed to work.
Why?
I'm not sure this is necessary but to shed some light on why I want to do this as opposed to retrofitting my existing layers: The current code is also used outside of a web service context and is consumed by other code internally. Retrofitting ServiceStack in to this layer would make every place that consumes it require ServiceStack's assemblies and be aware of the web service which is a concern I want separated from the lower code. We were previously using MVC/WCF to accomplish this goal but we want some of the features available from ServiceStack.
the current architecture looks like this:
data -> DAL -> discrete business logic -> composition -> web service
Hopefully that makes enough sense and I'm not being obtuse. If you would like any more details about what I want to do or why I'll try to update this post as soon as possible.
Thanks!
You might use the fallback route in order to provide your own routing mechanism.
Then you get the request.Path property and route using your own mapping of path:Function which can be stored in a simple dictionary.
Anyway, if you go this path I don't see much benefit in using servicestack. It seems you just need an http handler that routes requests to existing services.

Resources