Home > Enterprise >  URL scheme, should put ID in url or in parameter?
URL scheme, should put ID in url or in parameter?

Time:06-24

Suppose you want a url for books of a user

You can do

   1. /book/{user_id}
   2. /user/{user_id}/books
   3. /book?user_id={user_id}

When to use each of the above and why?

CodePudding user response:

When to use each of the above and why?

Path segments are a useful choice when you care about reference resolution, especially the ability to move about the identifier hierarchy using dot segments. See RFC 3986.

A query part with application/x-www-form-urlencoded key value pairs is convenient when you want to give a client the capability to specify a specific resource within a common space of similar resources via a boring HTML form.

It's also acceptable to use both: to have multiple resources that serve duplicate content.

You can use the Content-Location field to indicate where the enclosed representation is actually coming from. You can also use the canonical link relation to signal which resource is the "preferred" version.

CodePudding user response:

In general, the URL scheme would reflect the domain. e.g. if the domain was a library management system there would be a relationship between books and the users who have borrowed them. e.g. a URL that could return whether the user_id has borrowed a book could be:

/book/{book_id}/{user_id}

This isn't ideal as it's almost like RPC where you're calling a function that returns TRUE or FALSE. REST should return a representation of the current state of the object.

The query

which books has this user borrowed?

could be represented by:

/user/{user_id}/books

The query

which users have borrowed this book

could be represented by:

/book/{book_id}/users

To translate into a domain:

A User can Borrow Books

so the URL starts /user

a Book can be borrowed by Users

so the URL starts /book

Starting from either /user or /book you can then add more parts to each url to query the resource.

A query parameter is generally used to refine the result rather than influence the state of the resource. e.g. you could have different formats of the same representation:

/user/{user_id}/books?format=xml
/user/{user_id}/books?format=json
  • Related