Sources
HTTP APIs
Declare paginated REST, fan-out, POST, and OAuth2 jobs with sl.http.
sl.http describes REST jobs that run entirely in Rust; for worked examples see
HTTP APIs in the guide. Its
http connection sets auth, rate_limit, max_in_flight and
retries.
| Function | Meaning |
|---|---|
sl.http(source=None, *, headers=None, connection=None) |
Requests to the source’s connection, or connection, adding headers. Connection settings passed here fail, naming the key to set. |
api.paginate(path, *, paginator, params=None, select=None, on_status=None, fields=None, keep_record=None, method="GET", json_body=None, key=None, cells=None, select_missing="fail", error_path=None, transform=None) |
Every page of path. |
api.fan_out(path, *, over, concurrency=8, paginator=None, params=None, select=None, on_status=None, fields=None, keep_record=None, method="GET", json_body=None, key=None, cells=None, batch=None, select_missing="fail", error_path=None, key_path=None, transform=None) |
path once per key of over, concurrency at a time, as keys arrive. One request per key without a paginator. |
| Argument | Meaning |
|---|---|
params |
Query parameters. None values are left out; times go as ISO text. |
select |
Where the rows are: $, or a path such as $.data.items. See A missing select path. |
on_status |
Statuses read as no rows, such as {404: "skip"}. |
select_missing |
"empty" reads a response without select as no rows. |
key |
The placeholder this job’s keys fill as another fan-out’s over. |
over |
A paginate whose select picks keys ($.items[*].id fills {id}), a fan-out, or a list of values (one placeholder) or dicts (by name). |
The rest are below: fields, keep_record, key_path,
error_path, transform,
method, json_body, batch and
cells.
| Paginator | Next page |
|---|---|
sl.single() |
None: one request. |
sl.next_link(pointer) |
The URL at pointer, such as "$.next". |
sl.link_header() |
The Link header’s rel="next". |
sl.cursor(pointer, param, *, location="query") |
The token at pointer, sent back as param. |
sl.offset(param="offset", *, limit, limit_param="limit", location="query", read_ahead=None) |
Counts rows by limit; ends at a short page. |
sl.page_number(param="page", *, start=1, page_size=None, page_size_param="page_size", location="query", read_ahead=None) |
Counts pages; ends at an empty page, or a short page with page_size. |
location="body" puts a paginator’s values in a POST body. For read_ahead, see
Reading pages ahead.
| Cells | Columns |
|---|---|
sl.cells(pointer="$.cells", *, value="$.value", name) |
One column per name from each row’s cells at pointer. name is a path in each cell, such as "$.FIELDNAME", or one of the two below. |
sl.listed(path, *, key="columnId", id_key="id", name_key="title", by_position=False) |
The columns listed at path: a cell’s key matches a column’s id_key, or its position; name_key names it. |
sl.header_row() |
The first row names the columns, by position, and doesn’t load. |
- A run’s requests to one connection share its limits, across tables; separate
sqlload loadprocesses don’t. - Credentials go only to the connection’s origin; OAuth2 secrets only to
token_url. - Transport errors, 429 and 5xx are retried, honouring
Retry-After. Other error statuses fail, unlesson_statusskips them. Errors name the request, status and start of the body, secrets as***. - Reading a job’s rows in Python fails (rule
python_row_loop); usetransform.
Ending at a short page
Section titled “Ending at a short page”Without page_size, sl.page_number ends only at an empty page, so a fan-out whose keys fit in one
page sends two requests per key. With page_size, a short page ends the run:
api.fan_out( "/proofs/{id}/activities", over=ids, select="$.items", paginator=sl.page_number("page", page_size=100, page_size_param="count"),)page_size is sent as page_size_param (not in params); page_size_param=None sends nothing.
Until the API has shown it sends pages that long, a short page is checked with one more
request. If that has rows, the API caps its pages: paging goes on to an empty page and a warning
names the page_size to set. sl.offset checks a short first page the same way, but fails, naming
the limit to set.
Reading pages ahead
Section titled “Reading pages ahead”read_ahead=N (at most 100) on sl.offset or sl.page_number keeps up to N page requests open,
for an API with slow pages:
api.paginate("/invoices", paginator=sl.offset(limit=50, read_ahead=20))The first page is read alone; after a full one, open requests double each round up to N. Rows
still load in page order, and requests past the last page are dropped. max_in_flight caps every
table’s open requests together. sl.cursor, sl.next_link and sl.link_header refuse
read_ahead, as each address comes from the page before.
A missing select path
Section titled “A missing select path”A response without the select path fails the load; an empty list or null there is no rows. This
catches an API that answers an error with a 200 status:
GET https://api.shop.example/v1/orders?p=4: select "$.items" is not in the response, which holds the keys error; an API can answer an error with a 200 status, so check the response. For an API that leaves an empty list out, set select_missing="empty" to read such a page as no rowssl.next_link, sl.cursor and sl.link_header end at a response with no next page, which they
can’t tell from an error response; with select set, such a response usually fails as above.
Errors in a successful response
Section titled “Errors in a successful response”error_path names where a 200 response reports an error, such as EAM’s ErrorAlert, GraphQL’s
errors or Slack’s error. Any value there but null, false, "", [] or {} (0 included)
fails the table before that page’s rows load, with the value cut at 200 characters:
POST https://eam.example/axis/restservices/grids: the API reported an error at $.ErrorAlert: [{"Message":"Grid WSJOBS: you are not allowed to run this grid"}]It’s written like select, without [*], and checked on every response with rows or keys, but not
OAuth2 token responses.
Repeated pages
Section titled “Repeated pages”sl.cursor, sl.next_link and sl.link_header fail when the next position was already requested
for the same request or fan-out key, rather than load a page twice:
POST https://eam.example/axis/restservices/grids: cursor 2 repeated after page 2, so paging would read page 2 again; check the paginator's pointersl.offset and sl.page_number fail when a page repeats the one before, as when an API ignores
the parameter.
Transforming each page
Section titled “Transforming each page”transform= calls f(rows, ctx) once per page, in order, on the rows after select, fields
and cells; requests stay in Rust. As for a
files table’s transform, rows is a
pyarrow.Table and it returns or yields dicts, a pyarrow.Table or a DataFrame. Pass the function
(registered or not) or its @sl.transform name.
import json
import sqlload as sl
shop = sl.source("shop", connection="shop", write_strategy="replace")api = sl.http(shop)
@sl.transformdef order_lines(rows, ctx): for order in rows.to_pylist(): for line in json.loads(order["lines"]): yield {"region": ctx.key["region"], "order_id": order["id"], **line}
@shop.table(description="Order lines, one row per line, by region.")def lines(ctx): return api.fan_out( "/regions/{region}/orders", over=["north", "south"], select="$.orders", transform=order_lines, )-
ctx.unitis"page",ctx.pageits number in the request (from 1), andctx.keythe fan-out key’s fields (Nonein apaginateor withbatch=). -
Nested values arrive as JSON text:
json.loadsthem, or pick them withfields. -
Every page goes through, an empty last page included.
flatten,columnsandmaskapply. -
A function that raises, or returns something else, fails the table:
GET .../regions/north/orders: transform order_lines failed: .... -
planfails when a literaltransform="name"matches no registered function, or two:$ sqlload planErrors (1)└── raw.shop__lines└── reason transform order_line: no function is registered as order_line with @sl.transform; the registered ones are order_lines✗ Plan failed 1 error -
A fan-out’s
over=job refusestransform.
Multi-level fan-out
Section titled “Multi-level fan-out”A fan_out whose select picks keys can be another fan_out’s over, as deep as needed. Each
key keeps the fields of the keys above it; when they share a name, rename one with key=, as in
select="$.items[*].id", key="item_id".
@shop.table(description="Order notes.", write_strategy="append", cursor_column="order_id")def notes(ctx): orders = api.paginate( "/orders", paginator=sl.page_number("p"), params={"after": ctx.cursor_value}, select="$.items[*].order_id", ) items = api.fan_out("/orders/{order_id}/items", over=orders, select="$.items[*].item_id") return api.fan_out( "/orders/{order_id}/items/{item_id}/notes", over=items, paginator=sl.page_number("page"), select="$.items", )- Each level has its own paginator,
concurrencyandon_status. At most the levels’concurrencyplus one requests are in flight, within the connection’s limits. - Put an incremental cursor on the top level.
- Only the last level’s rows load, without the keys’ fields, so select an ID the response repeats.
- Errors name the keys that led to them, such as
/orders order_id=5 → /orders/5/items item_id=51 → GET .../notes?page=2: HTTP 500. planchecks that each placeholder comes from a level above.
Keys in a POST body
Section titled “Keys in a POST body”Keys also fill {placeholders} in json_body’s strings. A value that is only a placeholder, such
as "{order_id}", takes the key as returned, so a number stays a number; inside other text it’s
text. Braces around a bare name are a placeholder anywhere, "{orders{id}}" included; { id }
isn’t.
@shop.table(description="Items of each order.", write_strategy="append", cursor_column="order_id")def items(ctx): orders = api.paginate( "/orders", paginator=sl.page_number("p"), params={"after": ctx.cursor_value}, select="$.items[*].order_id", ) return api.fan_out( "/items/lookup", over=orders, method="POST", json_body={"ids": "{order_id}"}, batch=1000, select="$.items", )batch=N sends up to N keys per request, so {"ids": "{order_id}"} becomes {"ids": [1, 2, …]}.
Each batch is one request, retried whole; concurrency counts batches. A batched fan-out needs
json_body, takes keys only as whole body values, and can’t be another fan-out’s over.
Rows of cells
Section titled “Rows of cells”Some APIs return each row as a list of cells, such as [{"columnId": 7001, "value": "Bolt"}].
cells=sl.cells(...) turns each into one column per name, in Rust. name says where names are:
name |
Names come from | Example |
|---|---|---|
"$.FIELDNAME" |
A path in each cell. | EAM |
sl.listed("$.columns") |
The listed columns, matching a cell’s columnId to a column’s id, named by title. |
Smartsheet |
sl.listed("$.columns", by_position=True) |
The listed columns, by position. | |
sl.header_row() |
The first row’s cells, by position. | Google’s grid data |
@eam.table(description="Work orders.")def work_orders(ctx): return api.paginate( "/grids", method="POST", json_body={"GRID": {"NAME": "WSJOBS"}}, paginator=sl.cursor( "$.Result.ResultData.NEXTCURSORPOSITION", "$.CURSORPOSITION", location="body", ), select="$.Result.ResultData.DATARECORD", cells=sl.cells("$.DATAFIELD", value="$.FIELDVALUE", name="$.FIELDNAME"), error_path="$.ErrorAlert", )valueis a path, or a list tried in turn, as invalue=["$.value", "$.displayValue"].- Names go through
namingandrename:DueDateloads asdue_date. A new name is a new column, underon_schema_change. - The load fails on a nameless cell, two cells for one column, names differing only in case, a row
field named like a cells column, or (with
sl.listed) a non-empty cell whose column isn’t listed. A column with no cell in a row loadsNULL. sl.header_row()takes the first row of the first page, per fan-out key; for one sheet split into ranges, usesl.listed.fields=picks pivoted columns by the API’s names ({"qty": "$.Qty"}).
POST with a JSON body
Section titled “POST with a JSON body”method="POST" sends json_body as JSON with every request. With location="body", sl.offset,
sl.page_number and sl.cursor put their values in the body, at paths such as "$.page.cursor".
Each request and retry starts from a fresh copy; without json_body, from {}.
@shop.table(description="Orders.", write_strategy="append", cursor_column="updated_at")def orders(ctx): return api.paginate( "/orders/search", method="POST", json_body={"filter": {"updated_after": ctx.cursor_value}}, paginator=sl.cursor("$.meta.next", "$.page.cursor", location="body"), select="$.items", )- Dates, times and decimals go as text; wrap them in
int()orfloat()for a JSON number. json_bodyon aGET,location="body"without POST, or a body path through a non-object fails before any request.- A POST follows only 307 and 308 redirects; 301, 302 and 303 fail.
sl.next_linkandsl.link_headerresend the body and fail on another origin.
OAuth2
Section titled “OAuth2”The oauth2_client_credentials, oauth2_refresh_token and oauth2_password kinds of auth
fetch tokens from token_url; set them on the http connection. For
an example, see OAuth2 in the guide.
- One token per run serves the connection. It’s renewed before it expires and once on a 401, then
the request is retried. With
on_status={401: "skip"}, only a token over 30 seconds old is renewed. client_auth = "basic"(default) sends the form-encoded client ID and secret by HTTP basic auth, per RFC 6749;"post"sends them as form fields.token_urlmust behttps(httponly onlocalhost). Token errors name it, the status and the server’serroranderror_description.- A rotated refresh token isn’t saved, so an API that revokes the old one fails the next run; use client credentials there if offered.
oauth2_passwordrenews with the response’srefresh_token, else the password. Wrong credentials end the run with exit 1, without retrying.