Batch jobs
A file of addresses is not a loop over /v1/geocode. Submit it once, and the service works through it at your key's rate, keeps the job safe if a server goes away, and gives back one answer per row, in order, with your own ids on them. There is no separate batch price and no separate batch rate: each row takes one token from the same address bucket as a single geocode.
- Submit the file:
POST /v1/batch?format=csvor?format=jsonl. A job id comes back at once, with202. - Follow it:
GET /v1/batch/{id}says how far it has got and how many seconds are left. - Collect the answers when it is
done:GET /v1/batch/{id}/results, as CSV or JSON lines. - Delete it when you have them, if you do not want them kept:
DELETE /v1/batch/{id}.
The input file
The body of the POST is the file itself, UTF-8, at most 64 MiB and at most2,000,000 rows. A larger body is refused with 413; more rows with 400. Split anything bigger into several jobs.
CSV
id,address
cust-001,"Avenida Insurgentes Sur 1602, 03940"
cust-002,Museo Soumaya
cust-003,"Paseo de la Reforma 222, Ciudad de México"
cust-004,"Calle Madero 1, 06000"
cust-005,"Calle Que No Existe 99999, 03940"- The first non-blank line is the header. Column names are matched ignoring case, and otherwise exactly:
id, addresswith a space names a column" address", and the file is refused. - The address column is called
q,address,queryortext— whichever your warehouse calls it. It is required, and a row with it empty refuses the whole file. idis optional and comes back on the row's answer, so joining the results to your table does not depend on order.nearis optional: alat,lonfor that row, which filters it to the grid cell of about 10 km around the point. It contains a comma, so it must be quoted, or it splits into two columns.- Any other column is ignored.
- Quoting: a field may be in double quotes, and a quote inside a quoted field is doubled (
""). Spaces around a field's value are trimmed. - No line breaks inside a field, quoted or not: a line break always ends a row. Clean multi-line addresses into one line first.
- Blank lines are skipped, and Windows line endings are fine.
- A byte-order mark is not stripped. Spreadsheet exports labelled "CSV UTF-8" often begin with one, and it becomes part of the first column's name — so that column is not recognised. Strip it, or save without it.
Download the file above: addresses.csv. Its rows are chosen to show what comes back for a good address, a place, an address with a city, a wrong street and a street that does not exist.
JSON lines
{"id": "a1", "q": "Avenida Insurgentes Sur 1602, 03940"}
{"id": "a2", "q": "OXXO", "near": "19.4326,-99.1332"}
"Museo Soumaya"- One JSON object per line, with the address as
q— oraddress,queryortext— and optionallyidandnear. Other fields are ignored. idandnearare strings.{"id": 17, …}is refused,line 1:followed by the parser's reason; send"17".- A line that is not an object is the address itself, with any surrounding double quotes removed — the commonest thing a person has lying around is one address per line. It is not decoded as JSON, so write
México, notM\u00e9xico. - Blank lines are skipped.
Download it: addresses.jsonl.
When a file is refused
A file is checked whole before anything is stored, and one bad row refuses all of it:
| Status | Error | Means |
|---|---|---|
400 | that file has no rows | Empty, blank lines only, or a CSV header with nothing under it. |
400 | that file has no header row | A CSV body with no non-blank line. |
400 | no column named q, address, query or text | The CSV header has no address column — check for spaces and a byte-order mark. |
400 | row N: no address | The Nth CSV row after the header has an empty address. |
400 | line N: … | Line N of a JSON lines file (counting blank lines) did not parse, or lacks an address field. |
400 | N rows; the limit is 2000000 | Split the file. |
413 | — | Over 64 MiB. Split the file. |
400 | plain text | The body is not UTF-8 — a Latin-1 export, typically. Re-encode it. |
Submitting
curl -X POST "https://api.oslew.com/v1/batch?format=csv" \
-H "Authorization: Bearer $GEO_API_KEY" \
-H "Content-Type: text/csv" \
--data-binary @addresses.csvfrom oslew import Client
# The key is read from GEO_API_KEY.
client = Client(base_url="https://api.oslew.com")
answer = client.batch(
open("addresses.csv").read(),
format="csv",
content_type="text/csv",
)import { readFile } from "node:fs/promises";
import { Client } from "@oslew/client";
// The key is read from GEO_API_KEY.
const client = new Client({ baseUrl: "https://api.oslew.com" });
const answer = await client.batch(await readFile("addresses.csv", "utf8"), { format: "csv", contentType: "text/csv" });HTTP/1.1 202 Accepted
content-type: application/json
ratelimit-limit: 1
ratelimit-remaining: 1
ratelimit-reset: 1
{
"id": "KNBDU4TD1RrnARXRKn0jodCf",
"tenant": "docs-batch",
"state": "queued",
"rows": 5,
"done": 0,
"found": 0,
"rps": 1,
"format": "csv",
"created_at": 1795427402,
"updated_at": 1795427402,
"epoch": 1,
"owner": "docs-examples",
"heartbeat_at": 1795427402,
"parts": 0
}A real response, captured from the service at commit b8f4bde-dirty. Timing fields such as took_us differ on every call.
202 means the job is durable: the input is stored before the answer is sent, so once you hold an id, the job survives the server that accepted it. The body is the stored job:
| Field | Is |
|---|---|
id | 24 letters and digits. Keep it: it is how you follow, collect and cancel the job. |
state | queued. |
rows | Rows read from the file. |
done, found | Rows attempted, and rows that got a position. Both 0. |
rps | The rate the job is paced at: the submitting key's own address rate. This example was submitted with a key allowed one request a second, so its five rows take about five seconds. |
format | How the input was read. |
tenant | Your account's identifier. Jobs belong to the account, not the key. |
created_at, updated_at, heartbeat_at | Unix seconds. |
epoch, owner, parts | Which claim on the job is current, the server holding it, and how many output parts are written — bookkeeping for the takeover described below. |
The same, as JSON lines — the second row carries a near, the third is a bare address:
curl -X POST "https://api.oslew.com/v1/batch?format=jsonl" \
-H "Authorization: Bearer $GEO_API_KEY" \
-H "Content-Type: application/x-ndjson" \
--data-binary @addresses.jsonlfrom oslew import Client
# The key is read from GEO_API_KEY.
client = Client(base_url="https://api.oslew.com")
answer = client.batch(open("addresses.jsonl").read(), format="jsonl")import { readFile } from "node:fs/promises";
import { Client } from "@oslew/client";
// The key is read from GEO_API_KEY.
const client = new Client({ baseUrl: "https://api.oslew.com" });
const answer = await client.batch(await readFile("addresses.jsonl", "utf8"), { format: "jsonl" });HTTP/1.1 202 Accepted
content-type: application/json
ratelimit-limit: 1
ratelimit-remaining: 1
ratelimit-reset: 1
{
"id": "OnClPC2UT5EwVGsAwNp06sMK",
"tenant": "docs-batch",
"state": "queued",
"rows": 3,
"done": 0,
"found": 0,
"rps": 1,
"format": "jsonl",
"created_at": 1795427413,
"updated_at": 1795427413,
"epoch": 1,
"owner": "docs-examples",
"heartbeat_at": 1795427413,
"parts": 0
}A real response, captured from the service at commit b8f4bde-dirty. Timing fields such as took_us differ on every call.
The submission is itself a request on the address product and takes one token. The clients have the method asbatch; pass format with the file, and set the content type to match if you like — it is for your own logs, not for the service.
Following a job
GET /v1/batch/{id} answers where the job is. This five-row job was asked while it was under way:
HTTP/1.1 200 OK
content-type: application/json
ratelimit-limit: 20
ratelimit-remaining: 98
ratelimit-reset: 1
{
"created_at": 1795427402,
"done": 0,
"epoch": 1,
"error": null,
"found": 0,
"id": "KNBDU4TD1RrnARXRKn0jodCf",
"owner": "docs-examples",
"parts": 0,
"remaining_s": 5,
"rows": 5,
"rps": 1,
"state": "queued",
"updated_at": 1795427402
}A real response, captured from the service at commit b8f4bde-dirty. Timing fields such as took_us differ on every call.
And once it had finished:
curl "https://api.oslew.com/v1/batch/KNBDU4TD1RrnARXRKn0jodCf" \
-H "Authorization: Bearer $GEO_API_KEY"from oslew import Client
# The key is read from GEO_API_KEY.
client = Client(base_url="https://api.oslew.com")
answer = client.get_batch("KNBDU4TD1RrnARXRKn0jodCf")import { Client } from "@oslew/client";
// The key is read from GEO_API_KEY.
const client = new Client({ baseUrl: "https://api.oslew.com" });
const answer = await client.get_batch("KNBDU4TD1RrnARXRKn0jodCf");HTTP/1.1 200 OK
content-type: application/json
ratelimit-limit: 20
ratelimit-remaining: 98
ratelimit-reset: 1
{
"created_at": 1795427402,
"done": 5,
"epoch": 1,
"error": null,
"found": 5,
"id": "KNBDU4TD1RrnARXRKn0jodCf",
"owner": null,
"parts": 1,
"remaining_s": 0,
"rows": 5,
"rps": 1,
"state": "done",
"updated_at": 1795427406
}A real response, captured from the service at commit b8f4bde-dirty. Timing fields such as took_us differ on every call.
| Field | Is |
|---|---|
state | One of the five states below. |
rows, done, found | Rows in the file, rows attempted, rows that got a position. found counts positions, not right answers: a row answered with the wrong street is found. |
remaining_s | ceil((rows − done) / rps): the seconds the rest should take at the key's rate. 0 when done. |
rps | The paced rate. |
updated_at | When the job last wrote progress. It stops moving if the server running it is gone — and another takes over. |
error | Why it failed, when it did; otherwise null. |
parts, epoch, owner | Output parts written, the current claim, and the server holding it — null once it is done. |
state | Means |
|---|---|
queued | Accepted and not yet reporting progress — or handed back by a server shutting down, until another picks it up. |
running | Being worked through at the key's rate. |
done | Every row answered. The results can be collected. |
failed | Stopped; error says why. The results cannot be collected. |
cancelled | Deleted by its owner. The input and output are gone. |
Progress is written every 500 rows, and at the end. Between those checkpoints done,found and remaining_s stand still, and a job still reports queued until its first checkpoint — which is why the running job above says queued and done: 0: a job of five rows goes from queued to done without ever showing running. Readremaining_s as a schedule, not a stopwatch.
Asking for results too early
Results exist only for a done job. Before that, /results answers 409 — not404, because the job exists and a poller needs to tell the two apart — with the progress a poller needs:
HTTP/1.1 409 Conflict
content-type: application/json
ratelimit-limit: 20
ratelimit-remaining: 99
ratelimit-reset: 1
{
"done": 0,
"error": "that job is queued",
"remaining_s": 5,
"rows": 5
}A real response, captured from the service at commit b8f4bde-dirty. Timing fields such as took_us differ on every call.
error names the state: that job is queued, running, failed orcancelled. On queued or running, wait remaining_s and ask again; on the other two, stop.
Pacing: the key's own bucket
A job takes one token per row from the submitting key's address bucket — the same bucket that key's geocodes, validations, time zone lookups and batch requests draw on — and it takes them as fast as the bucket refills. That is the whole of the pricing: bulk and interactive work share one budget, per key, and neither has its own. See rate limits.
Three consequences, all worth planning for:
- A job at 20 rows a second uses all of a 20-a-second key. While it runs, other requests on the same key compete with it for tokens and are refused with
429when they lose. That includes your own status polls: a poll from the job's key takes a token a row would have used, and can itself be refused. We saw exactly this while capturing the examples on this page. - Poll slowly, or from another key.
remaining_ssays how long to wait; polling every few seconds on a job with hours left only slows it. Buckets are per key but jobs belong to the account, so a second key of the same account can poll, collect and cancel the job without touching the job's tokens. - Give bulk work its own key. A backfill running on the key your checkout uses will crowd the checkout out. Mint a key for batch work, and the two cannot starve each other.
How long: rows divided by the key's rate. Twenty a second is 72,000 rows an hour; two million rows is about 27.8 hours, a day and a night, and the job says so in remaining_s rather than pretending otherwise. At high rates the geocoding itself can be slower than the bucket — a measured run on a key allowed 50 a second did 34.4 rows a second — so treat remaining_s as a floor.
Collecting results
GET /v1/batch/{id}/results?format=csv or ?format=jsonl (the default), whatever the input format was. There is one output row per input row, in input order, carrying yourid. Each row was geocoded exactly as /v1/geocode would with limit=1, the row's own near, and interpolation on — so tied_at_top is still counted over at least eight candidates, and a single answer does not hide ambiguity.
curl -G "https://api.oslew.com/v1/batch/KNBDU4TD1RrnARXRKn0jodCf/results" \
-H "Authorization: Bearer $GEO_API_KEY" \
--data-urlencode 'format=csv'from oslew import Client
# The key is read from GEO_API_KEY.
client = Client(base_url="https://api.oslew.com")
text = client.batch_results("KNBDU4TD1RrnARXRKn0jodCf", format="csv")
print(text)import { Client } from "@oslew/client";
// The key is read from GEO_API_KEY.
const client = new Client({ baseUrl: "https://api.oslew.com" });
const text = await client.batch_results("KNBDU4TD1RrnARXRKn0jodCf", { format: "csv" });
console.log(text);id,q,name,lat,lon,precision,precision_m,confidence,tied_at_top,formatted,house_number,street,locality,region,postcode,country,source,release,license,error
cust-001,"Avenida Insurgentes Sur 1602, 03940",AVENIDA INSURGENTES SUR 1602,19.364069672979937,-99.18198831998704,rooftop,6.756173533775122,0.72772276,1,"AVENIDA INSURGENTES SUR 1602, Ciudad de México, 03940, MX",1602,AVENIDA INSURGENTES SUR,Ciudad de México,,03940,MX,overture-addresses,2026-08-19.0,"permissive (per-source, see record)",
cust-002,Museo Soumaya,Museo Soumaya,19.44062110346353,-99.2046595360656,poi,6.756173533775122,0.5,1,"Museo Soumaya, Miguel Hidalgo, CMX, MX",,,Miguel Hidalgo,CMX,,MX,overture-places,2026-08-19.0,CDLA-Permissive-2.0,
cust-003,"Paseo de la Reforma 222, Ciudad de México",AVENIDA PASEO DE LA REFORMA 222,19.42905748976803,-99.1621778772732,rooftop,6.756173533775122,0.352459,1,"AVENIDA PASEO DE LA REFORMA 222, Ciudad de México, 06600, MX",222,AVENIDA PASEO DE LA REFORMA,Ciudad de México,,06600,MX,overture-addresses,2026-08-19.0,"permissive (per-source, see record)",
cust-004,"Calle Madero 1, 06000",CALLE TACUBA 1,19.435964227232493,-99.1402969208942,rooftop,6.756173533775122,0.5,1,"CALLE TACUBA 1, Ciudad de México, 06000, MX",1,CALLE TACUBA,Ciudad de México,,06000,MX,overture-addresses,2026-08-19.0,"permissive (per-source, see record)",
cust-005,"Calle Que No Existe 99999, 03940",CALLE HERA,19.365038165737747,-99.17921975464016,street,6.756173533775122,0.5,13,"CALLE HERA, Ciudad de México, 03940, MX",,CALLE HERA,Ciudad de México,,03940,MX,overture-addresses,2026-08-19.0,"permissive (per-source, see record)",A real response, captured from the service at commit b8f4bde-dirty.
{"id":"cust-001","q":"Avenida Insurgentes Sur 1602, 03940","name":"AVENIDA INSURGENTES SUR 1602","lat":19.364069672979937,"lon":-99.18198831998704,"precision":"rooftop","precision_m":6.756173533775122,"confidence":0.72772276,"tied_at_top":1,"normalized":{"house_number":"1602","street":"AVENIDA INSURGENTES SUR","locality":"Ciudad de México","postcode":"03940","country":"MX","formatted":"AVENIDA INSURGENTES SUR 1602, Ciudad de México, 03940, MX"},"provenance":{"name":"overture-addresses","release":"2026-08-19.0","license":"permissive (per-source, see record)"}}
{"id":"cust-002","q":"Museo Soumaya","name":"Museo Soumaya","lat":19.44062110346353,"lon":-99.20465953606559,"precision":"poi","precision_m":6.756173533775122,"confidence":0.5,"tied_at_top":1,"normalized":{"locality":"Miguel Hidalgo","region":"CMX","country":"MX","formatted":"Museo Soumaya, Miguel Hidalgo, CMX, MX"},"provenance":{"name":"overture-places","release":"2026-08-19.0","license":"CDLA-Permissive-2.0"}}
{"id":"cust-003","q":"Paseo de la Reforma 222, Ciudad de México","name":"AVENIDA PASEO DE LA REFORMA 222","lat":19.429057489768034,"lon":-99.16217787727321,"precision":"rooftop","precision_m":6.756173533775122,"confidence":0.352459,"tied_at_top":1,"normalized":{"house_number":"222","street":"AVENIDA PASEO DE LA REFORMA","locality":"Ciudad de México","postcode":"06600","country":"MX","formatted":"AVENIDA PASEO DE LA REFORMA 222, Ciudad de México, 06600, MX"},"provenance":{"name":"overture-addresses","release":"2026-08-19.0","license":"permissive (per-source, see record)"}}
{"id":"cust-004","q":"Calle Madero 1, 06000","name":"CALLE TACUBA 1","lat":19.435964227232493,"lon":-99.1402969208942,"precision":"rooftop","precision_m":6.756173533775122,"confidence":0.5,"tied_at_top":1,"normalized":{"house_number":"1","street":"CALLE TACUBA","locality":"Ciudad de México","postcode":"06000","country":"MX","formatted":"CALLE TACUBA 1, Ciudad de México, 06000, MX"},"provenance":{"name":"overture-addresses","release":"2026-08-19.0","license":"permissive (per-source, see record)"}}
{"id":"cust-005","q":"Calle Que No Existe 99999, 03940","name":"CALLE HERA","lat":19.365038165737747,"lon":-99.17921975464016,"precision":"street","precision_m":6.756173533775122,"confidence":0.5,"tied_at_top":13,"normalized":{"street":"CALLE HERA","locality":"Ciudad de México","postcode":"03940","country":"MX","formatted":"CALLE HERA, Ciudad de México, 03940, MX"},"provenance":{"name":"overture-addresses","release":"2026-08-19.0","license":"permissive (per-source, see record)"}}A real response, captured from the service at commit b8f4bde-dirty.
| Column | Is |
|---|---|
id | Your id for the row, as given; empty (CSV) or absent (JSON lines) if you gave none. |
q | The address as you sent it. |
name | The matched place or address, as the data names it. |
lat, lon | The position. |
precision, precision_m | What the position locates, and how far off it can be. |
confidence | Calibrated: how often answers of this shape were right. |
tied_at_top | How many candidates shared the best rank. More than 1 means the address as sent names several places. |
formatted, house_number, street, locality, region, postcode, country | The address in parts and in one line — in JSON lines, the normalized object. A part the match does not have is empty or absent. |
source, release, license | Where the answer came from and under what licence — in JSON lines, the provenance object, the same one /v1/geocode returns. Store it with the row: it is what says you may keep it. See data and licensing. |
error | no match when nothing matched at all, or this row's own refusal — a near that does not parse, for instance. The position and address columns are then empty. One bad row never fails the job. |
The CSV quotes a field containing a comma, a quote or a line break, and doubles quotes inside it; read it with a CSV parser, not by splitting on commas. JSON lines omit a field that has no value rather than writingnull.
Read every row's evidence before you trust it. All five rows above were found, and two of them are not the address that was asked for:
cust-001andcust-003arerooftopanswers with confidence 0.99 and 0.97: located.cust-002is the museum, with confidence 0.5 — a place named without context is a shape the calibration has not measured, not a doubtful answer.cust-004asked for Calle Madero 1 and got Calle Tacuba 1, arooftopon another street in the same postcode.precisionsays what the position locates, not that it is the address you meant; confidence 0.8 is the flag — it is the level of a partial match, andstreetdiffers from what was sent.cust-005asked for a street that does not exist and gotCALLE HERMES, a street row in that postcode that shares only the word calle with it, andtied_at_top: 8: many streets tie on that one word. Nor was 99999 interpolated — there is nothing to place it between, and interpolation never extrapolates.
A batch row carries no why. To see how a doubtful row matched, send its q to/v1/geocode on its own.
Size. Results come back as one response: about 12 MB of JSON lines per 50,000 rows, so roughly half a gigabyte for two million. The clients read a response into memory; for a large job, stream it to a file:
curl -H "Authorization: Bearer $GEO_API_KEY" \
"https://api.oslew.com/v1/batch/$JOB_ID/results?format=jsonl" -o results.jsonlListing jobs
curl "https://api.oslew.com/v1/batch" \
-H "Authorization: Bearer $GEO_API_KEY"from oslew import Client
# The key is read from GEO_API_KEY.
client = Client(base_url="https://api.oslew.com")
answer = client.list_batches()import { Client } from "@oslew/client";
// The key is read from GEO_API_KEY.
const client = new Client({ baseUrl: "https://api.oslew.com" });
const answer = await client.list_batches();HTTP/1.1 200 OK
content-type: application/json
ratelimit-limit: 20
ratelimit-remaining: 98
ratelimit-reset: 1
{
"jobs": [
{
"created_at": 1795427413,
"done": 0,
"found": 0,
"id": "OnClPC2UT5EwVGsAwNp06sMK",
"rows": 3,
"state": "cancelled",
"updated_at": 1795427413
},
{
"created_at": 1795427402,
"done": 5,
"found": 5,
"id": "KNBDU4TD1RrnARXRKn0jodCf",
"rows": 5,
"state": "done",
"updated_at": 1795427406
}
]
}A real response, captured from the service at commit b8f4bde-dirty. Timing fields such as took_us differ on every call.
GET /v1/batch lists the account's jobs, newest first, with id, state,rows, done, found, created_at and updated_at.limit defaults to 50 and is clamped to 1–200; there is no cursor, so it shows at most the 200 most recent. Cancelled and failed jobs stay in the list.
Cancelling, and deleting
curl -X DELETE "https://api.oslew.com/v1/batch/OnClPC2UT5EwVGsAwNp06sMK" \
-H "Authorization: Bearer $GEO_API_KEY"The clients leave DELETE out on purpose; send it with curl when you mean it.
HTTP/1.1 200 OK
content-type: application/json
ratelimit-limit: 20
ratelimit-remaining: 99
ratelimit-reset: 1
{
"id": "OnClPC2UT5EwVGsAwNp06sMK",
"state": "cancelled"
}A real response, captured from the service at commit b8f4bde-dirty. Timing fields such as took_us differ on every call.
DELETE /v1/batch/{id} marks the job cancelled and deletes its input file and every output part. Nothing it produced can be collected afterwards: /results answers409, that job is cancelled. The job's record stays, so it is still listed and still answersGET. A running job notices within 256 rows and stops.
It works on a finished job too, and that is how a job's data is removed; the job then reads cancelled. A done job's input and output are kept until you DELETE it — there is no expiry — so if the file held customer addresses, collect the results and then delete the job. The clients leave DELETE out on purpose; send it with curl, or your HTTP library, when you mean it.
When a job fails
A job stops with state: failed and a reason in error:
the key running this job was revoked— the submitting key was revoked or its account suspended. Rotate keys after a large job, not during one.the {plan} plan no longer includes address— the key's plan changed to one without the address product.the stored input is goneorthe stored input no longer parses— the job could not be resumed after a takeover.
A failed job's results cannot be collected, even for the rows it had done. Fix the cause and submit the file again.
Durability and takeover
A job is not tied to the server that accepted it. Its input, progress and output live in shared storage, and the server working on it renews a lease as it writes progress. If that server stops — a crash, a restart — another takes the job over once the lease has gone 90 seconds without renewal, and resumes at the last complete output part. Parts are 50,000 rows, so up to that many rows are geocoded again, and take tokens again; the output is still one row per input row, with no gap and no duplicate. A server shutting down cleanly for a deploy hands its jobs back at once rather than waiting out the lease.
One difference after a takeover: the server that resumes a job does not know which key submitted it, so the rest of the job is not paced by the key's bucket, and revoking the key no longer stops it. It may finish sooner thanremaining_s said. To stop a job, DELETE it.
Retention and ownership
- No expiry. A job's input and results are kept until you delete it.
- Jobs belong to the account. Any key of the account that submitted a job can follow, collect, list and cancel it.
- Another account's job does not exist for you. Its id answers
404, the same as an id nobody issued:
HTTP/1.1 404 Not Found
content-type: application/json
ratelimit-limit: 20
ratelimit-remaining: 97
ratelimit-reset: 1
{
"error": "no job with that id"
}A real response, captured from the service at commit b8f4bde-dirty. Timing fields such as took_us differ on every call.
A complete client
Submit with the key whose rate should pace the job; follow it from a second key of the same account, waiting about half of remaining_s between polls; collect; and sort the rows by what their evidence says.
import json
import os
import time
from oslew import Client, RateLimited
API = "https://api.oslew.com"
# The job is paced by this key (GEO_API_KEY). Uploads and downloads can be large.
jobs = Client(base_url=API, timeout=600)
# Polls from a second key of the same account do not take the job's tokens.
# Without GEO_POLL_KEY this falls back to GEO_API_KEY, and polls compete with the job.
poller = Client(os.environ.get("GEO_POLL_KEY"), base_url=API)
def submit(path: str) -> str:
fmt = "csv" if path.endswith(".csv") else "jsonl"
with open(path, encoding="utf-8") as f:
job = jobs.batch(f.read(), format=fmt,
content_type="text/csv" if fmt == "csv" else "application/x-ndjson")
return job["id"]
def wait(job_id: str) -> dict:
while True:
try:
job = poller.get_batch(job_id)
except RateLimited as e:
time.sleep(e.retry_after or 1) # the bucket is empty: wait as told
continue
if job["state"] == "done":
return job
if job["state"] in ("failed", "cancelled"):
raise RuntimeError(f"job {job_id} is {job['state']}: {job['error']}")
# About half the time left, never under 5 s and never over 10 minutes.
time.sleep(min(max(job["remaining_s"] / 2, 5), 600))
def collect(job_id: str) -> list:
text = jobs.batch_results(job_id, format="jsonl")
return [json.loads(line) for line in text.splitlines() if line]
def triage(rows: list) -> dict:
out = {"located": [], "review": [], "ambiguous": [], "street": [], "missing": []}
for r in rows:
if "error" in r:
out["missing"].append(r) # "no match", or this row's own refusal
elif r["tied_at_top"] > 1:
out["ambiguous"].append(r) # several places fit equally: add context
elif r["precision"] in ("street", "address"):
out["street"].append(r) # the street, not the door
elif r["confidence"] < 0.9:
out["review"].append(r) # a partial match, or an unmeasured shape
else:
out["located"].append(r) # rooftop, interpolated, or a place
return out
job_id = submit("addresses.csv")
wait(job_id)
rows = triage(collect(job_id))
print({k: len(v) for k, v in rows.items()})import { readFile } from "node:fs/promises";
import { Client, RateLimited } from "@oslew/client";
const API = "https://api.oslew.com";
// The job is paced by this key (GEO_API_KEY). Uploads and downloads can be large.
const jobs = new Client({ baseUrl: API, timeoutMs: 600_000 });
// Polls from a second key of the same account do not take the job's tokens.
// Without GEO_POLL_KEY this falls back to GEO_API_KEY, and polls compete with the job.
const poller = new Client({ baseUrl: API, apiKey: process.env.GEO_POLL_KEY });
const sleep = (s: number) => new Promise((r) => setTimeout(r, s * 1000));
async function submit(path: string): Promise<string> {
const csv = path.endsWith(".csv");
const job = await jobs.batch(await readFile(path, "utf8"), {
format: csv ? "csv" : "jsonl",
contentType: csv ? "text/csv" : "application/x-ndjson",
});
return job.id;
}
async function wait(id: string) {
for (;;) {
let job;
try {
job = await poller.get_batch(id);
} catch (e) {
if (!(e instanceof RateLimited)) throw e;
await sleep(e.retryAfter ?? 1); // the bucket is empty: wait as told
continue;
}
if (job.state === "done") return job;
if (job.state === "failed" || job.state === "cancelled") {
throw new Error("job " + id + " is " + job.state + ": " + (job.error ?? ""));
}
// About half the time left, never under 5 s and never over 10 minutes.
await sleep(Math.min(Math.max((job.remaining_s ?? 0) / 2, 5), 600));
}
}
interface Row {
id?: string;
q: string;
name?: string;
lat?: number;
lon?: number;
precision?: string;
confidence?: number;
tied_at_top: number;
error?: string;
}
async function collect(id: string): Promise<Row[]> {
const text = await jobs.batch_results(id, { format: "jsonl" });
return text.split("\n").filter(Boolean).map((line) => JSON.parse(line) as Row);
}
function triage(rows: Row[]) {
const out: Record<string, Row[]> = { located: [], review: [], ambiguous: [], street: [], missing: [] };
for (const r of rows) {
if (r.error !== undefined) out.missing.push(r); // "no match", or this row's refusal
else if (r.tied_at_top > 1) out.ambiguous.push(r); // several places fit: add context
else if (r.precision === "street" || r.precision === "address") out.street.push(r);
else if ((r.confidence ?? 0) < 0.9) out.review.push(r); // partial match, or unmeasured
else out.located.push(r); // rooftop, interpolated, or a place
}
return out;
}
const id = await submit("addresses.csv");
await wait(id);
const sorted = triage(await collect(id));
console.log(Object.fromEntries(Object.entries(sorted).map(([k, v]) => [k, v.length])));On the five rows above, that sorts cust-001 and cust-003 as located, cust-002and cust-004 for review, and cust-005 as ambiguous. The threshold is yours to choose; the point is that every row carries enough to choose it. The clean a customer CSVexample takes this further.
Endpoints
/v1/batchaddressGeocode a file. A job id comes back at once; the rows are worked through at the rate the key's plan sustains.