KScript docs
EN

KScript.Net

HTTP requests (@api) and downloads.

Import it at the top of a script:

<import package="KScript.Net" />
import KScript.Net

KScript.Net makes network requests, so its examples can't run inside the docs. Copy one into a .ks.xml file and run it with kscript.

Commands

Commands are called with @, in any expression: @name(arguments).

#@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

Makes an HTTP request and returns the response. Give an absolute HTTP(S) URL or a path such as '/api/notes' to call the project's own routes in this process.
ParameterTakes
url requiredstring. The absolute URL or project route to request.
options optionalmap. Configure this request with the fields below.
post optionalany. Sends this body with POST: @api('/notes', post: { title: 'Ship it' }). Maps and lists are sent as JSON, base64 values as binary data, and other values as UTF-8 text. Without post:, put:, patch: or delete:, the request is a GET.
put optionalany. Sends this body with PUT.
patch optionalany. Sends this body with PATCH.
delete optionalany. Sends a DELETE. delete: true sends no body; anything else is sent as the body.
bearer optionalstring. An Authorization: Bearer header with this token.
timeout optionalduration. The same as options.timeout: 5s.
retries optionalnumber. The same as options.retries: 3.
as optionaltype. Checks the response succeeded and reads its JSON as this type. @api($url, as: Note) is @api($url)->check()->convert(from: json, as: Note).
encoding optionalone of these words: 'json'|form|multipart. How a map body is sent: json (the default), form (application/x-www-form-urlencoded, as an HTML form or an OAuth token endpoint expects) or multipart (multipart/form-data, where base64 values and uploaded files become file parts).
query optionalmap. Values added to the URL's query string: query: { page: 2, tag: ['a', 'b'] }. A list is sent once per item.

#options fields

FieldTypeDefaultDescriptionExample value
headersmap{ 'User-Agent': 'kscript' }Header names and values. Set User-Agent to identify the client or Content-Type to override the body format header.{ Accept: 'application/json' }
timeoutduration100sMaximum wait for an outbound HTTP(S) request. A number is seconds. In-process requests to project routes ignore this field.30s
retriesnumber0Additional attempts on transient outbound failures for GET, HEAD and OPTIONS.2
retry_delayduration100msTime between retry attempts.250ms
encodingstringjsonHow a map body is sent (json, form or multipart), the same as encoding:.form
querymap{}Values added to the URL's query string, the same as query:.{ page: 2 }
max_sizenumber100000000The most bytes of response body to read. A larger answer stops with a Limit error instead of filling the memory.5000000

Arguments can be named: @api(…, options: …, post: …).

Example
<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

#@download(url, to, overwrite?: bool, timeout?: duration) → string

Downloads a URL to a file and returns the file's full path. Folders are created as needed, and a relative path is from the script's folder. overwrite: false keeps a file that is already there. timeout: is how long the whole download may take (30 minutes unless given), so a server that stops answering can't hold the script forever.
ParameterTakes
url requiredany value
to requiredany value
overwrite optionala flag: overwrite or not overwrite
timeout optionalduration

Arguments can be named: @download(…, to: …, overwrite: …).

Example
<do>@download('https://example.com/data.csv', 'data/data.csv')</do>
@download('https://example.com/data.csv', 'data/data.csv')

#@http_client(base_url: string, options?: map) → fn

Returns a callable HTTP client. Call it with a relative path and optional request options.
ParameterTakes
base_url requiredstring
options optionalmap

Arguments can be named: @http_client(…, options: …).

Example
<let name="github" value="@http_client('https://api.github.com', { headers: { Accept: 'application/vnd.github+json' } })" />
<let name="repo" value="$github('/repos/dotnet/runtime')->convert(from: json)" />
<echo>{ $repo.full_name }</echo>
$github = @http_client('https://api.github.com', { headers: { Accept: 'application/vnd.github+json' } })
$repo = $github('/repos/dotnet/runtime')->convert(from: json)
echo $repo.full_name

#@parse_query(text: string) → map

Parses URL query text into a map. Repeated names have a list of values in order.
ParameterTakes
text requiredstring
Example
<let name="query" value="@parse_query('page=2&amp;tag=a&amp;tag=b')" />
<echo>{ $query.page } { $query.tag }</echo>
$query = @parse_query('page=2&tag=a&tag=b')
echo "{ $query.page } { $query.tag }"

#@query_string(map) → string

A map as a URL query: a=1&b=two. A list is written once per item (tag=a&tag=b), the form @parse_query reads back.
Example
<let name="filters" value="{ page: 2, tag: ['a', 'b'] }" />
<echo>{ @query_string($filters) }</echo>
$filters = { page: 2, tag: ['a', 'b'] }
echo @query_string($filters)

#@with_http_stub(handler: fn(request: map), work: fn) → any

Runs work with outbound @api and HTTP client calls intercepted by handler(request).
ParameterTakes
handler requiredfn. A stub that handles one request map.
work requiredfn

Arguments can be named: @with_http_stub(…, work: …).

Example
<let name="name" value="@with_http_stub(fn(request) => { status: 200, body: { name: 'stub' } }, fn() => @api('https://api.example.com/me')->convert(from: json).name)" />
<echo>{ $name }</echo>
$name = @with_http_stub(fn(request) => { status: 200, body: { name: 'stub' } }, fn() => @api('https://api.example.com/me')->convert(from: json).name)
echo $name

#@with_loopback_json(port: port, action: fn, timeout?: duration) → any

Connects to a JSON Lines service on IPv4 loopback, returns action(connection), and closes it. Each transaction has one timeout (2m by default).
ParameterTakes
port requiredport
action requiredfn
timeout optionalduration

Arguments can be named: @with_loopback_json(…, action: …, timeout: …).

Example
<echo>{ @with_loopback_json(8765, fn(connection) => $connection->transaction(fn(stream) => $stream->read())) }</echo>
echo @with_loopback_json(8765, fn(connection) => $connection->transaction(fn(stream) => $stream->read()))

Methods

On response values: ->header(), ->check()

On loopback_json_connection values: ->transaction()

On loopback_json_stream values: ->send(), ->read()