Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ElpsySec's avatar

Restful API with Relationships (user vs post vs user.post)

Note: This is a question about style and best practices. I know how to actually accomplish the act of retrieving a model with a relationship, I just want to know if there is a restful way of doing it without using the relationships restful route or querying something like /model/id/with-relationship-foo.

What is the best way to distinguish between requesting a model in from your restful api, and a model with a certain relationship?

Let's say I want a user, I request /user/1.

User
{
    id: 1
    name: "Bobby Tables"
}

Let's say I want that user's posts, I request /user/1/post.

Posts
[
    {
        id: 1,
        text: "Hello World",
        user_id: 1
    },
    ...
]

However, how would I request a user model with the posts? Such that I would receive JSON similar to:

User
{
    id: 1,
    name: "Bobby Tables",
    posts: [
        {post}, 
        {post}, 
        {post}
    ]
}

Thanks! Bonus question: do ya'll use singular or plural route names?

0 likes
3 replies
ElpsySec's avatar

@Prez Thanks for the response, but I already know how to do it. What I want to know is how to distinguish routes. As in, how would a route differ from returning Users::all() and Users::with('posts')->all(); Seemingly both would be '/user' (with route named something like 'user.index'). The thing is, I don't want to always pass the relationships to the user for security reasons (or if they just don't need the data). And I don't want to have to pass a flag or value that says get the posts relationship, or get the permissions relationship. So i was wondering if there was a restful way to do this.

I know I could distinguish what data i pass by prefixing the route with the usertype (for example /admin/user vs /client/user or /subscriber/user). These could all return only the relationships relevant to them. However, I was wondering if there was a way that you could take care of it in routes such as requesting /user/id/post/id/user or if that was bad form.

jekinney's avatar

I use route groups to clean my route files up. But, like you mentioned, does it make sense and easy to consume.

/users/all

/users/posts/all

Or

/users

/users/posts

With a single user

/user/{id}

/user/{id}/posts

/user/{id}/post/{post_id}

Biggest thing for me is consistency. Other routes should adhere to similar routing. This is where proper planning and scope docs help to ensure a "Oops" gotta squeeze this in somewhere is minimized.

Please or to participate in this conversation.