Home > Net >  How do I separate my controllers If I have nested resources? (JAVA Spring)
How do I separate my controllers If I have nested resources? (JAVA Spring)

Time:03-11

I'm developing a forum API in JAVA using Spring and I been refactoring my URLS so they are nested using a maximum of 2 levels.

For example I have the following endpoints in UserPostController:
(GET) /api/v1/users/{username}/posts
(GET) /api/v1/users/{username}/posts/{postId}
(POST) /api/v1/users/{username}/posts
(PUT) /api/v1/users/{username}/posts/{postId}
(DELETE) /api/v1/users/{username}/posts/{postId}

(The posts cannot exists if they aren't linked to an existing user)

But I also wanted an endpoint that let me get ALL existing Posts of ALL Users so I figure I't will be something like:
(GET) /api/v1/posts

I created another controller called "PostController" for that but only with that endpoint.

The problem is that I have another relationships like this one, for example between Post and Comments, and I will end up creating a lot of Controllers for the cases when I want to GET ALL CHILDRENS OF ALL PARENTS. I'm sure there is another better way.

Edit: I also have to mention that the base path for the UserPostController is "/api/v1/users/{username}/posts".

CodePudding user response:

Your current REST-Design for basic input/output posts is well designed. If I try to give it a name I would call it the Posts-Service.

I suggest to create a second REST-Microservice for that aggregation issue (let me call it Aggregation-Service) because:

  1. I think you need lower performance on the Posts-Service than on the Aggregation-Service. Because ALL existing Posts of ALL Users and GET ALL CHILDRENS OF ALL PARENTS might return hughe data and looks to be read-only. So they have different performance requirements than your Posts-Service and you might balance them differently.

  2. I think the aggregation might have changes (i.e.: new ordering/filtering-functionality) that can be compleatly detached from the development of the Posts-Service. You can release changes from Aggregation-Service and Posts-Service seperatly or at least be able to make different A/B tests.

  3. Posts-Service require a security-concpet. Aggregation Service might not need a security-concept.

Kind Regards

CodePudding user response:

You could create such an DashboardController (your words) and create a path having so-called Matrix-Parameters. They seperate pre-questionmark-requests using the ; as part of the URL.

Matrix parameters are designed exactly for your case but not well-accepted in the REST-Community. Anyway, this is the Matrix-Solution:

http://www.example.com/api/v1/dashboard/all;parentId=123

http://www.example.com/api/v1/dashboard/all

  • Related