#@api(url: string, options?: map, post?: any, put?: any, patch?: any, delete?: any, bearer?: string, timeout?: duration, retries?: number, as?: type, encoding?: 'json'|form|multipart, query?: map) → response
发起一个 HTTP 请求并返回响应。请提供绝对的 HTTP(S) URL,或者像
'/api/notes' 这样的路径,以便在本进程中调用项目自身的路由。| 参数 | 接受 |
|---|---|
url 必需 | 字符串。要请求的绝对 URL 或项目路由。 |
options 可选 | 映射。使用下面的字段配置此请求。 |
post 可选 | 任意。通过 POST 发送此请求体:@api('/notes', post: { title: 'Ship it' })。映射和列表以 JSON 发送,base64 值以二进制数据发送,其他值以 UTF-8 文本发送。若未使用 post:、put:、patch: 或 delete:,则请求为 GET。 |
put 可选 | 任意。通过 PUT 发送此请求体。 |
patch 可选 | 任意。通过 PATCH 发送此请求体。 |
delete 可选 | 任意。发送 DELETE 请求。delete: true 不发送请求体;其他任何值都作为请求体发送。 |
bearer 可选 | 字符串。带有此令牌的 Authorization: Bearer 请求头。 |
timeout 可选 | 时长。与 options.timeout: 5s 相同。 |
retries 可选 | 数字。与 options.retries: 3 相同。 |
as 可选 | 类型。检查响应是否成功,并将其 JSON 读取为此类型。@api($url, as: Note) 为 @api($url)->check()->convert(from: json, as: Note)。 |
encoding 可选 | 一个单词:'json'|form|multipart。映射请求体的发送方式:json(默认)、form(application/x-www-form-urlencoded,HTML 表单或 OAuth 令牌端点所需的格式)或 multipart(multipart/form-data,其中 base64 值和上传文件会成为文件部分)。 |
query 可选 | 映射。添加到 URL 查询字符串中的值:query: { page: 2, tag: ['a', 'b'] }。列表会按每一项分别发送。 |
#options 个字段
| 字段 | 类型 | 默认 | 说明 | 示例值 |
|---|---|---|---|---|
headers | map | { 'User-Agent': 'kscript' } | 请求头名称和值。设置 User-Agent 以标识客户端,或设置 Content-Type 以覆盖请求体格式请求头。 | { Accept: 'application/json' } |
timeout | duration | 100s | 发出出站 HTTP(S) 请求时的最长等待时间。数字单位为秒。对项目路由的进程内请求会忽略此字段。 | 30s |
retries | 数字 | 0 | 对于 GET、HEAD 和 OPTIONS,在出现临时出站失败时额外重试的次数。 | 2 |
retry_delay | duration | 100ms | 重试尝试之间的间隔时间。 | 250ms |
encoding | string | json | 映射请求体的发送方式(json、form 或 multipart),与 encoding: 相同。 | form |
query | map | {} | 添加到 URL 查询字符串中的值,与 query: 相同。 | { page: 2 } |
max_size | 数字 | 100000000 | 读取响应正文的最大字节数。响应超过该值时,会以 Limit 错误停止,而不是占满内存。 | 5000000 |
参数可以命名:@api(…, options: …, post: …)。
示例
<kscript>
<import package="KScript.Net" />
<let name="url" value="$args->first() ?? 'https://httpbin.org/anything'" />
<let name="reply" value="@api($url, post: { title: 'Ship it' }, options: { headers: { Accept: 'application/json' } }, timeout: 30s)" />
<echo>{ $reply->check().status }</echo>
</kscript>import KScript.Net
$url = $args->first() ?? 'https://httpbin.org/anything'
$reply = @api($url, post: { title: 'Ship it' }, options: { headers: { Accept: 'application/json' } }, timeout: 30s)
echo $reply->check().status