在REST API中支持多种语言 [英] Supporting multiple languages in a REST API
问题描述
我收集了一些要为其创建REST API(我的第一个REST API)的城市.每个城市都有许多与语言无关的事物,例如成立日期和人口数量.城市还具有取决于语言的事物,例如标题和简短描述.内部城市文件具有以下格式:
I have a collection of cities for which I'm creating a REST API (my first REST API). Each city has a number of language independent things, such as founding date and population count. Cities also have things that depend on the language, such as the title and a short description. Internally the city documents have this format:
{
"population": 9042,
"name": {
"en": "Berlin",
"nl": "Berlijn",
// ...
},
// ...
}
我的API的用户始终只希望查看特定语言的城市信息,并获取类似以下内容的信息:
The users of my API always want to view the city info for a specific language only, and get back something like:
{
"population": 9042,
"name": Berlin,
// ...
}
我已经通过/cities/:id/:language_code
(例如 cities/123/en
)访问了这些代码.现在,我要实现城市列表: GET/cities
.那里也需要请求的语言.由于这会导致/cities/:language_code
,因此,给人留下的印象是将其放在url的末尾不是一个好主意,并且怀疑我使用会更好/en/cities/...任何...
.
I've made these accessible via /cities/:id/:language_code
, for instance cities/123/en
. Now I want to implement listing of cities: GET /cities
. There the requested language is also needed. Since this would result in /cities/:language_code
, I'm getting the impression putting this at the end of the url is not a good idea, and suspect I'll be better off with /en/cities/...whatever...
.
这在REST API中通常是如何完成的?那里有任何大型的,实现良好的API就是一个很好的例子吗?
How is this typically done in REST APIs? Any big, nicely implemented, API out there that is a good example?
推荐答案
REST API基于HTTP协议,因此它们可以使用标头,这些标头通常用于定义首选的语言环境.
REST API's are based upon HTTP protocol, so they can use the headers, that are traditionaly used to defined the prefered locale.
因此,我将为此使用 Accept-Language
参数.
So I would use a Accept-Language
parameter for this.
# Request
GET /cities/.... HTTP/1.1
Host: www.example.org
Accept-Language: en,en-US,fr;q=0.6
会给:
{
"population": 9042,
"name": Berlin,
// ...
}
这篇关于在REST API中支持多种语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!