Search code examples
restroutesbackendweb-development-server

In general, would it be redundant to have two GET routes for users (one for ID and one for username)?


I'm building a CRUD for users in my rest API, and currently my GET route looks like this:

get("/api/users/:id")

But this just occured to me: what if a users tries to search for other users via their username?

So I thought about implementing another route, like so:

get("api/users/username/:id")

But this just looks a bit redundant to me. Even more so if ever my app should allow searching for actual names as well. Would I then need 3 routes?

How would I handle having to search for a user via their username?


Solution

  • how they would handle having to search for a user via their username?

    How would you support this on a web site?

    You would probably have a form; that form would have an input control that would allow the user to provide a user name. When the user submit the form, the browser would copy the form input controls into an application/x-www-form-urlencoded document (as described by the HTTP standard), then substitute that document as the query_part of the form action, and submit the query.

    So the resulting request would perhaps look like

    GET /api/users?username=GuiMendel HTTP/x.y
    

    You could, of course, have as many different forms as you like, with different combinations of input controls. Some of those forms might share actions, but not necessarily.

    so I could just have my controller for GET "/api/users" redirect to an action based on the inputs?

    REST doesn't care about "controllers" -- that's an implementation detail; the whole point is that the client doesn't need to know how the server produces a representation of the resource, we just need to know how to ask for it (via the "uniform interface").

    Your routing framework might care a great deal, but again that's just another implementation detail hiding behind the facade.

    for example, there were no inputs, it would return all users (index), but with the input you suggested, it would filter out only users whose usernames matched the input? Did I get it right?

    Yup, that's fine.

    From the point of view of a REST client

    /api/users
    /api/users?username=GuiMendel
    

    These identify different resources; the two resources don't have to have any meaningful relationship with each other at all. The machines don't care (human beings do care, so we normally design our identifiers in such a way that at least some human beings have an easy time of it -- for example, we might optimize our identifiers to make things easy when operators are reading the access logs).