자체 API 호출하기
KScript.Net의 @api()는 주소 대신 경로를 받아, 같은 프로세스에서 네트워크를 거치지 않고 프로젝트 자체의 라우트에 요청합니다:
<import package="KScript.Net" />
<let name="notes" value="@api(/api/notes)->check()->convert(from: json)" />
<let name="added" value="@api(/api/notes, post: { title: 'Ship it' })" />
<echo value="$added.status" /> <!-- 201 -->import KScript.Net
$notes = @api(/api/notes)->check()->convert(from: json)
$added = @api(/api/notes, post: { title: 'Ship it' })
echo $added.status // 201이 기능은 프로젝트(kscript.json가 있는 폴더) 안의 페이지, 테스트, 스크립트, 그리고 라우트에서 사용할 수 있습니다. 인자와 응답은 주소를 사용할 때와 같으며, post: 등 다른 메서드도 같습니다. 그다음에는 options: { headers: … }, .status, ->convert(from: json), ->header(name) 등이 이어집니다. 라우트가 없는 경로는 404가 됩니다.
메서드와 본문은 하나의 명명된 인자이며, 사람들이 가장 많이 설정하는 옵션도 각각 인자를 가집니다:
| 인자 | 기능 |
|---|---|
post: { title: 'Ship it' }, put: $note, patch: $changes |
이 메서드를 이 본문과 함께 보냅니다. 맵이나 리스트는 JSON으로 보내집니다. 본문이 없으면 요청은 GET입니다. |
delete: true |
본문 없이 DELETE를 보냅니다. 그 밖의 값은 본문으로 보내집니다. |
bearer: $token |
헤더에 Authorization: Bearer …를 추가합니다. |
timeout: 5s, retries: 3 |
options의 같은 필드와 동일합니다. |
as: Note |
응답이 성공해야 하며, 응답의 JSON은 Note 레코드가 됩니다. |
encoding: form, encoding: multipart |
맵 본문을 JSON 대신 HTML 폼(application/x-www-form-urlencoded) 또는 multipart/form-data로 보냅니다. |
query: { page: 2 } |
값을 URL의 쿼리 문자열에 추가합니다. 리스트는 항목마다 한 번씩 전송됩니다. |
많은 API는 JSON 대신 폼을 요구합니다. 예를 들어 OAuth 토큰 엔드포인트가 그렇고, 파일 업로드에는 multipart가 필요합니다. multipart 본문에서 base64 값은 파일로 전송되며, $request.files에서 업로드된 파일은 이름과 타입을 유지하므로 라우트가 업로드를 그대로 넘길 수 있습니다:
<import package="KScript.Net" />
<let name="token" value="@api('https://auth.example.com/token', post: { grant_type: 'client_credentials', client_id: $id }, encoding: form)->convert(from: json)" />
<do>@api('https://files.example.com/upload', post: { title: 'Avatar', file: $files.avatar[0] }, encoding: multipart, bearer: $token.access_token)</do>
<do>@api('https://api.example.com/search', query: { q: 'cats', tag: ['a', 'b'] })</do>import KScript.Net
$token = @api('https://auth.example.com/token', post: { grant_type: 'client_credentials', client_id: $id }, encoding: form)->convert(from: json)
@api('https://files.example.com/upload', post: { title: 'Avatar', file: $files.avatar[0] }, encoding: multipart, bearer: $token.access_token)
@api('https://api.example.com/search', query: { q: 'cats', tag: ['a', 'b'] })자체 라우트는 encoding: form와 JSON을 사용하며, multipart는 네트워크상의 주소를 위한 것입니다.
post: null와 delete: false는 아무것도 보내지 않으므로, 헬퍼는 자신의 인자를 그대로 넘길 수 있습니다: @api($url, post: $post, delete: $delete). 옵션을 두 방식으로 모두 주면 오류가 되므로, 요청은 각 항목을 한 번만 지정합니다.
@api()는 원격 주소와 로컬 주소 모두에 기본적으로 User-Agent: kscript를 보냅니다. 자신만의 클라이언트를 사용하려면 options: { headers: { 'User-Agent': 'my-app' } }를 전달하세요. 이는 해당 요청 하나에만 적용됩니다.
쿠키와 로그인
다른 요청에 응답하는 중에 이루어진 요청, 예를 들어 페이지가 API를 호출하거나 라우트가 다른 라우트를 호출하는 경우에는, 응답 중인 요청의 Cookie와 Authorization 헤더가 함께 전송되므로 API는 같은 로그인 사용자를 인식합니다. 다른 값을 보내려면 직접 headers를 지정하세요. 전달한 Cookie 헤더는 라우트의 $cookies로 읽히며, 이는 kscript serve가 읽는 방식과 같습니다. 응답이 설정한 쿠키는 이후 요청으로 절대 전달되지 않습니다:
<import package="KScript.Net" />
<!-- The route reads $cookies.sb_guest as '0f8f'. -->
<let name="reply" value="@api(/board, options: { headers: { Cookie: 'sb_guest=0f8f' } })" />
<!-- The cookies the response set, such as { ks_session: '...', sb_guest: '...' }. -->
<echo value="$reply.cookies" />
<!-- A list when the response set more than one. -->
<echo value="$reply.headers['Set-Cookie']" />import KScript.Net
// The route reads $cookies.sb_guest as '0f8f'.
$reply = @api(/board, options: { headers: { Cookie: 'sb_guest=0f8f' } })
// The cookies the response set, such as { ks_session: '...', sb_guest: '...' }.
echo $reply.cookies
// A list when the response set more than one.
echo $reply.headers['Set-Cookie']한 헤더가 Set-Cookie처럼 여러 번 보내지면 .headers에서 목록이 되고, ->header(name)는 첫 번째 값을 줘요. .cookies에는 응답이 설정한 각 쿠키의 이름과 값이 담겨요. 요청이 서로 중첩되면 8번째에서 멈추므로, 자기 자신을 호출하는 라우트는 멈추지 않고 오류가 나요.
fullstack 프로젝트 템플릿의 Notes 예제가 이렇게 동작해요. 페이지들은 노트를 /api/notes에서 가져오므로, 페이지와 다른 클라이언트가 같은 API를 공유해요.