跳转到内容

RESTful 基础

RESTful 由定义了 xidl RESTful 风格的代码生成。RESTful 由三个部分组成:

  1. 基础 RESTful。
  2. HTTP Stream。
  3. HTTP Security。

当使用 RESTful 生成器时,xidlc 可以将 .idl 文件中的接口编译为 REST API。

interface HelloWorld {
void say_hello(string name);
};
Terminal window
$ xidlc gen -o out rust-axum api.idl

RESTful 可以通过注解配置 HTTP 方法、路径、参数来源、媒体类型、安全要求等细节。

使用 @get 注解可以指定方法类型,使用 @path("/hello") 可以指定路径, 同时也支持在 @get(path = "/hello") 里直接指定路径:

interface HelloWorld {
@get(path = "/hello")
void say_hello(string name);
};

支持下面的方法类型:@get@post@put@delete@patch

路径参数中可以使用路由模板,其格式如下:

  • 普通路径变量:/users/{id}
  • catch-all 路径:/files/{*path}
  • query template:/users/{id}{?lang,region}

出现在路由模板中的参数默认情况下需要和方法参数同名,例如:

interface UserApi {
@get(path = "/users/{id}")
string getUser(string id);
};

如果需要重命名路由参数,可以在方法参数上使用 @path @rename("...") 注解,例如:

interface UserApi {
@get(path = "/users/{x-id}{?x-lang}")
string getUser(
@path @rename("x-id") string user_id
@query @rename("x-lang") @optional string lang
);
};

RESTful 支持多种来源的参数,这可以通过注解明确指定,例如:

interface UserApi {
@get(path = "/users/{id}")
string getUser(
@path string user_id,
@query string locale,
@header @rename("USER_NAME") string name,
@cookie string session_id,
@body string payload
);
};

使用 @Consumes@Produces 注解可以指定请求和响应的媒体类型。它们都支持接口级默认值和方法级覆盖。

@Consumes("application/json")
@Produces("application/json")
interface ScopeApi {
@post(path = "/v1/default")
string defaultScope(string name);
@post(path = "/v1/form")
@Consumes("application/x-www-form-urlencoded")
string submitForm(string name, uint32 age);
@get(path = "/v1/msgpack/{id}")
@Produces("application/msgpack")
string getPacked(@path @rename("id") string id);
};

建议把它理解成:

  • 接口级注解是“默认配置”
  • 方法级注解是“局部覆盖”

如果你的接口大多数操作都用同一种请求/响应媒体类型,接口级默认值通常更干净。

可以使用 @cors 注解添加对 cors 的支持,目前支持两种形式:

  • @cors:开启 CORS
  • @cors("https://console.example.com", "https://admin.example.com"):只允许这些来源

例如:

@cors
interface UserApi {
@get(path = "/users/{id}")
string getUser(@path @rename("id") string id);
@cors("https://console.example.com", "https://admin.example.com")
@post(path = "/users")
void createUser(string name);
};
注解作用范围含义
@cors接口对接口中的所有方法启用 cors
@cors(“domain1”, “domain2”)接口对接口中的所有方法允许来自 domain1 和 domain2 的请求
@cors方法启用 cors
@cors(“domain1”, “domain2”)方法允许来自 domain1 和 domain2 的请求

RESTful 可以将方法标记为已废弃,有三种写法:

  • @deprecated
  • @deprecated("2026-01-01")
  • @deprecated(since = "...", after = "...")

它们可以放在:

  • 接口上
  • 方法上
  • attribute 上

实践上推荐:

  • 想表达“已经不建议使用”,但没有具体时间点:用 @deprecated
  • 想表达“从某天开始废弃”:用 @deprecated("...")
  • 想同时表达废弃时间和计划移除窗口:用 @deprecated(since = "...", after = "...")

接口级 @deprecated 会被其中的方法和 attribute 继承;方法级再声明时,以更具体的方法级为准。

如果参数可为空,需要将其标记为 @optional

interface UserApi {
@get(path = "/users/{id}")
string getUser(
@path string user_id,
@query @optional string locale
);
};