How do I call an API for every row without making one request per row?
Every order has a country code and you need the country name and currency from a lookup API. One request per row is slow and hits rate limits. The API accepts up to 100 codes in one request, so the rows should travel in groups.
Grouping is not something your script has to do. A pipe that declares batch mode receives an array of records per line, and the runner decides where to cut.
A pipe is a data-processing step with declared inputs and outputs; a pipeline connects pipes.
What you need
- The
openflangecommand, release v0.0.1:bashgo install github.com/openflange/openflange-go/cmd/openflange@v0.0.1 python3onPATH. Only the standard library is used: nothing to install with pip.- An empty directory. Create the files below in it under exactly these names and run every command from that directory.
- No account and no key. Nothing leaves your machine.
Steps
1. Start the stand-in API and save the input
fake-api.py is not a real service: it is a local stand-in on 127.0.0.1:18089 that answers from a table of six countries and writes one line per request to api.log. It lets you run the recipe without a network. The first command starts it in the background.
#!/usr/bin/env python3
"""A LOCAL STAND-IN for a remote API, so the recipe runs offline. Not a real service.
POST /v1/countries {"codes": ["GB", "FR"]}
200 {"results": [{"code": "GB", "name": "United Kingdom", "currency": "GBP"}, ...]}
One result per code, in order; an unknown code gives {"code": ..., "name": null, "currency": null}.
At most 100 codes per request (HTTP 413 beyond that). Listens on 127.0.0.1:18089 only and appends
one line per request to api.log, so you can see how many requests a run made.
"""
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
COUNTRIES = {
"GB": ("United Kingdom", "GBP"), "FR": ("France", "EUR"), "DE": ("Germany", "EUR"),
"JP": ("Japan", "JPY"), "BR": ("Brazil", "BRL"), "US": ("United States", "USD"),
}
MAX_CODES = 100
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))))
codes = body.get("codes", [])
status = 200 if self.path == "/v1/countries" and len(codes) <= MAX_CODES else (413 if len(codes) > MAX_CODES else 404)
results = []
for code in codes if status == 200 else []:
name, currency = COUNTRIES.get(code, (None, None))
results.append({"code": code, "name": name, "currency": currency})
with open("api.log", "a", encoding="utf-8") as log:
log.write(f"POST {self.path} {status} codes={len(codes)}\n")
payload = json.dumps({"results": results}).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def log_message(self, *args): # quiet: api.log is the only log
pass
if __name__ == "__main__":
HTTPServer(("127.0.0.1", 18089), Handler).serve_forever(){"order":1001,"country":"GB","total":120}
{"order":1002,"country":"FR","total":80}
{"order":1003,"country":"JP","total":4300}
{"order":1004,"country":"GB","total":15}
{"order":1005,"country":"XX","total":60}
{"order":1006,"country":"BR","total":210}
{"order":1007,"country":"DE","total":99}
{"order":1008,"country":"US","total":45}python3 fake-api.py > /dev/null 2>&1 & echo $! > api.pid; sleep 1This command prints nothing.
2. Write the pipe
The batch block of the manifest is the whole switch: at most 100 records per batch, and no record waits longer than 200 ms. The permissions say that the script starts a subprocess and sends data to one address.
---
spec: openflange.org/pipe/v0.1
id: country-lookup-batch
version: 0.1.0
title: Country lookup through an API (Python, batch mode)
description: Adds `countryName` and `currency` to every record by calling an HTTP API once per batch of records instead of once per record.
license: Apache-2.0
keywords: [api, http, enrichment, batch, python, recipe]
maturity: experimental
scope: record
cardinality: one-to-one
batch:
maxItems: 100 # the API accepts at most 100 codes per request
maxWaitMs: 200 # never hold a record back for more than 200 ms
inputs:
records:
description: 'Records with a `country` member holding a two-letter code, e.g. {"order": 1001, "country": "GB"}.'
schema:
format: json-schema
definition: {type: object, required: [country]}
outputs:
records:
description: The same records, in order, with `countryName` and `currency` added (both null when the API does not know the code).
schema:
format: json-schema
definition:
type: object
required: [countryName, currency]
parameters:
url:
type: string
default: "http://127.0.0.1:18089/v1/countries"
description: 'Endpoint that accepts {"codes": [...]} and answers {"results": [...]}, one result per code, in order.'
timeoutSeconds:
type: integer
default: 10
minimum: 1
maximum: 120
description: Time limit for one request. A request that fails or times out fails the run; it is not retried.
implementation:
type: script
language: python
path: lookup.py
permissions:
subprocess: true
network: ["127.0.0.1:18089"]
remoteData: ["127.0.0.1"]
---
# Country lookup through an API (Python, batch mode)
Implements the [OpenFlange](https://openflange.org/) specification.
A Python script (standard library only) in **batch mode**: the runner writes
one JSON array of up to 100 records per line to its standard input, the script
makes **one HTTP request per line** and answers with one JSON array of the
same length.
- `network` and `remoteData`: the `country` member of every record is sent to
the endpoint. With the default `url` that is the stand-in `fake-api.py` on
this machine; point `url` at a real host and the data leaves the machine,
so change both permissions with it.
- A failed request fails the run (`E_RUNTIME`). Nothing is retried and
nothing is dropped.#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""country-lookup-batch: one HTTP request per batch of records.
Batch mode, delivery `lines`: every line on stdin is a JSON array of records
(a batch); every line on stdout is the JSON array of the results, same length,
same order.
"""
import json
import os
import sys
import urllib.request
with open(os.environ["OPENFLANGE_CONFIG"], encoding="utf-8") as f:
PARAMS = json.load(f)["parameters"]
def lookup(codes):
"""One request for the whole batch: {"codes": [...]} -> {"results": [...]}."""
request = urllib.request.Request(
PARAMS["url"], data=json.dumps({"codes": codes}).encode(), method="POST",
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(request, timeout=PARAMS["timeoutSeconds"]) as response:
results = json.load(response)["results"]
if len(results) != len(codes):
raise ValueError(f"the API answered {len(results)} results for {len(codes)} codes")
return results
for line in sys.stdin:
batch = json.loads(line)
try:
results = lookup([record.get("country") for record in batch])
except (OSError, ValueError, KeyError) as error:
print(f"country-lookup-batch: request failed: {error}", file=sys.stderr)
sys.exit(1)
out = [{**record, "countryName": result["name"], "currency": result["currency"]} for record, result in zip(batch, results)]
sys.stdout.write(json.dumps(out, ensure_ascii=False, separators=(",", ":")))
sys.stdout.write("\n")
sys.stdout.flush() # one answer per batch: the runner waits for it3. Run it
Three grants, one for each permission the manifest asks for. Then look at the log of the stand-in.
openflange run . --grant subprocess --grant network=127.0.0.1:18089 --grant remoteData=127.0.0.1 < orders.ndjson{"order":1001,"country":"GB","total":120,"countryName":"United Kingdom","currency":"GBP"}
{"order":1002,"country":"FR","total":80,"countryName":"France","currency":"EUR"}
{"order":1003,"country":"JP","total":4300,"countryName":"Japan","currency":"JPY"}
{"order":1004,"country":"GB","total":15,"countryName":"United Kingdom","currency":"GBP"}
{"order":1005,"country":"XX","total":60,"countryName":null,"currency":null}
{"order":1006,"country":"BR","total":210,"countryName":"Brazil","currency":"BRL"}
{"order":1007,"country":"DE","total":99,"countryName":"Germany","currency":"EUR"}
{"order":1008,"country":"US","total":45,"countryName":"United States","currency":"USD"}
completed in 120ms — records: 8 recordscat api.logPOST /v1/countries 200 codes=8Eight records, one request.
4. Make the batches smaller
--batch 3 lowers the batch size for this run: three requests of 3, 3 and 2 codes, appended to the same log. The output is the same eight records.
openflange run . --grant subprocess --grant network=127.0.0.1:18089 --grant remoteData=127.0.0.1 --batch 3 --output records=enriched.ndjson < orders.ndjsoncompleted in 75ms — records: 8 recordscat api.logPOST /v1/countries 200 codes=8
POST /v1/countries 200 codes=3
POST /v1/countries 200 codes=3
POST /v1/countries 200 codes=25. Test it, then stop the stand-in
The tests need the stand-in running. One of them pins the batch size to one record and expects the same output: a pipe in batch mode must not depend on where its input is cut.
# requires: python3, and fake-api.py listening on 127.0.0.1:18089 (start it first)
spec: openflange.org/test/v0.1
pipe: ..
tests:
- name: adds the country name and the currency to every record
grants: {subprocess: true, network: ["127.0.0.1:18089"], remoteData: ["127.0.0.1"]}
inputs:
records:
values:
- {order: 1, country: GB}
- {order: 2, country: JP}
expect:
outputs:
records:
values:
- {order: 1, country: GB, countryName: United Kingdom, currency: GBP}
- {order: 2, country: JP, countryName: Japan, currency: JPY}
- name: an unknown code is kept, with nulls
grants: {subprocess: true, network: ["127.0.0.1:18089"], remoteData: ["127.0.0.1"]}
inputs:
records:
values: [{order: 3, country: XX}]
expect:
outputs:
records:
values: [{order: 3, country: XX, countryName: null, currency: null}]
- name: the same output with one record per request
grants: {subprocess: true, network: ["127.0.0.1:18089"], remoteData: ["127.0.0.1"]}
batch: {maxItems: 1, maxWaitMs: 0}
inputs:
records:
values:
- {order: 1, country: GB}
- {order: 2, country: JP}
expect:
outputs:
records:
values:
- {order: 1, country: GB, countryName: United Kingdom, currency: GBP}
- {order: 2, country: JP, countryName: Japan, currency: JPY}
- name: an endpoint that does not answer fails the run
grants: {subprocess: true, network: ["127.0.0.1:18089", "127.0.0.1:9"], remoteData: ["127.0.0.1"]}
parameters: {url: "http://127.0.0.1:9/v1/countries", timeoutSeconds: 2}
inputs:
records:
values: [{order: 1, country: GB}]
expect:
status: failed
error: {code: E_RUNTIME}
- name: without the grants the pipe is refused before anything is sent
inputs:
records:
values: [{order: 1, country: GB}]
expect:
status: failed
error: {code: E_PERMISSION}openflange test .tests/country-lookup-batch.test.yaml
ok adds the country name and the currency to every record
ok an unknown code is kept, with nulls
ok the same output with one record per request
ok an endpoint that does not answer fails the run
ok without the grants the pipe is refused before anything is sent
ok 5 tests passed in 1 file (333ms)kill $(cat api.pid)This command prints nothing.
Limits
- The API is a stand-in. No real service was called. For a real one change
urland both permissions (network,remoteData), and the data of every record leaves your machine. - No retries, no back-off, no rate limiting, no authentication. A request that fails or times out fails the run. An API key would be a declared secret (
permissions.secrets), never a parameter; that is not shown here. - Requests are sequential: one batch at a time.
- A batch is a transport unit, not a group with meaning. The runner cuts by
maxItemsandmaxWaitMs;--batchcan only lower the declared values. - The pipe is one-to-one: every answer must have exactly as many elements as its batch.
- A subprocess is not sandboxed by this runner: the
networkgrant is checked before the run, it does not confine the Python process. - Batch mode is specified in RFC 0003 and explained in Batch mode.
Related pages
- This recipe uses no standard pipe: it is one pipe of its own.
- Concepts behind it: Batch mode, Permissions
- Building this with an AI agent? Give it the guide for agents: the rules, the file layout and the commands to check its own work.
Every command on this page was run on Linux with openflange 0.0.1 (go1.27.1 linux/amd64), built from openflange-go commit 11cf8cc5378d70858724b16aa937d7f3b98c085d. The files and the recorded output are kept in the site repository under sites/dev/test/fixtures/recipes/api-per-row-batch/, and a test compares this page with them byte for byte.