Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-lingual REST resources - URL naming suggestions

Is there a REST best practice for GETting resources in different languages. Currently, we have

www.mysite.com/books?locale=en

I know we can use the accept-language header but is it better for us to do

www.mysite.com/books/en or www.mysite.com/books.en

or does it not matter?

like image 857
Ilyas Patel Avatar asked Nov 20 '11 21:11

Ilyas Patel


People also ask

Which URL pattern is recommended when working with one resources and a collection of resources?

Relative vs Absolute. It is strongly recommended that the URLs generated by the API should be absolute URLs. The reason is mostly for ease of use by the client, so that it never has to find out the correct base URI for a resource, which is needed to interpret a relative URL.

How long can a rest url be?

The REST API supports Uniform Resource Locators (URLs) with a length of up to 6000 characters. To avoid exceeding this limit, it is important to be aware of URL encoding.


2 Answers

If you're trying to have your server return different translations or localized versions of the same books (in other words, the same resource from a RESTful perspective), then use Accept-Language because the resource is the same but the representation is different based on the client's needs.

However if you're trying to return completely different books based on the client's locale (say, returning books written in French if you know that the user is in France) then the URIs should be different since different resources would be returned. At this point, you're talking more about a query request more than anything else. For what it's worth, the /books/en approach sounds reasonable. Another approach would be to add the locale or language as a resource parameter to GET as /books?lang=en.

like image 52
Brian Kelly Avatar answered Sep 28 '22 11:09

Brian Kelly


I think best way would be to implement this following way:

  1. HTTP's Accept-Language header
  2. Language prefix in URI such as /en/books/...

In other words you can accept language from both sources. Implementation will be following:

  1. Check if Accept-Language header is provided and keep this in the variable;
  2. If request URI starts with /en, /fr or other known language codes(that are supported by your system) Overwrite language variable with this new value, strip it from URI i.e. if URI is /en/books you will end up with /books.
  3. If there is no language provided, keep default language in variable for example "en"

With this approach you can make sure that a) path routing will be language agnostic and your system will work uniformly with paths; b) language handling/negotiation will be completely separated from your scripts. You can use language information in your scripts without even knowing what was the source and how it was requested.

like image 35
ioseb Avatar answered Sep 28 '22 10:09

ioseb