One client, every API
No code generation. It reads the discovery document when it connects and knows the collections, methods, filters, sort keys and types from there.
Tools · Use an API · v0.2.1
restep for PythonRestep, pythonicOne client for every Restep API: pages you iterate, typed values on the way out, local validation, one exception per error code and idempotency keys you never have to think about.
Python 3.10 or later · pip install restep-py
No code generation. It reads the discovery document when it connects and knows the collections, methods, filters, sort keys and types from there.
A filter the API does not offer, a limit past max_limit, an enum value that does not exist: the same exception the server would raise, without the round trip.
except restep.PreconditionFailed, except restep.UnsupportedParameter. Each carries code, parameter, detail and the whole problem.
Python 3.10 or later and urllib. restep.aio is the same API with await, on httpx if you have it.
restep.connect(url) reads the discovery document at the root. If the root is taken by something else, it follows the root’s rel="service-desc" links, JSON ones first. With no discovery document at all, it assumes core only. A restep that does not follow the grammar of 1.1, or another major version ("2.0", "1.00"), raises restep.UnsupportedVersion: that API is not Restep 1, and it does not fall back to core either. api.version and api.pre_release tell a draft or a candidate apart, without doing anything different with it.Decimal, int and float for decimal, number and integer; date, datetime with a time zone and timedelta for date, datetime and duration; bool only for boolean.validate=True (the default), what discovery says the server would reject is rejected before sending, with the exception the server would give. Those exceptions carry local = True; the same except handles both.application/json, and a literal + in the query as %2B. create gets a fresh Idempotency-Key when the API announces writes, and keeps it across retries; not without credentials where the server declares "anonymous": false (7.1). update is a Merge Patch. if_match takes an ETag or the item you read, from which it takes _etag.dicts, JSON as it was sent: a decimal stays a string. get, create and update copy the item’s strong ETag into _etag, and list items bring their own _etag when the server sends it, so what you read can go straight back as if_match. Every 4xx or 5xx becomes an exception from its problem+json; a Deprecation header, a restep.RestepDeprecationWarning.The token and the headers go only to the API’s origin (4.3), never to a link that points elsewhere, and links with a scheme other than https or the root’s are not followed (3). Redirects are not followed. Members and values of discovery it does not know are ignored, along with what they qualify (4.2).
Python 3.10 or later. No dependencies; httpx only for the async version.
pip install restep-py
pip install "restep-py[async]" # with httpx
On PyPI it is restep-py, and it imports as restep. The restep package on PyPI is a different project: do not pip install restep.
import restep
api = restep.connect("https://api.example.com/", token="…", language="en")
for book in api["books"].iter(filter={"year": {"ge": 2025}}):
print(book["title"])
All of these ran against the reference server (PORT=18080 node restep-server.mjs), with the El Marcapáginas bookshop data.
>>> api = restep.connect("http://localhost:18080/")
>>> api
<restep.Api http://localhost:18080/ profiles=['cache', 'core', 'query', 'relations', 'writes'] collections=['books', 'products', 'categories', 'authors', 'reviews']>
>>> api.version, api.pre_release
('1.0-draft.6', 'draft.6')
>>> api.collections
{'books': <restep.Collection books /books>, 'products': <restep.Collection products /products>, 'categories': <restep.Collection categories /categories>, 'authors': <restep.Collection authors /authors>, 'reviews': <restep.Collection reviews /books/{book_id}/reviews>}
>>> api.singletons
{'shop': <restep.Singleton shop /shop>}
>>> api.deprecations
[{'kind': 'sort', 'name': 'year', 'announced': '2026-11-20T00:00:00Z', 'sunset': '2027-06-01T00:00:00Z', 'where': 'books'}]
>>> api.status()
True
>>> from decimal import Decimal
>>> books = api["books"]
>>> page = books.list(filter={"price": {"le": Decimal("20")}, "category": ["novela-negra", "poesia"]},
... sort="-rating", fields=["title", "price"], limit=2, count=True)
>>> page.items
[{'id': '30', 'title': 'Cuaderno de faros', 'price': '12.00', '_etag': '"7d807adf8890d30c"'}, {'id': '7', 'title': 'La niebla de Portugalete', 'price': '18.50', '_etag': '"5a8458498e20a142"'}]
>>> page.total, page.total.estimated
(Total(4, estimated=False), False)
>>> page.next_page().items
[{'id': '12', 'title': 'El último ferry', 'price': '16.90', '_etag': '"3f229ea9fc9865da"'}, {'id': '15', 'title': 'Lluvia sobre Deusto', 'price': '14.95', '_etag': '"6ec168acd48f8e5e"'}]
>>> [b["id"] for b in books.iter(filter={"year": {"ge": 2025}}, limit=2)] # every page, two at a time
['21', '23', '50', '7']
>>> books.count(filter={"rating": {"null": True}})
Total(1, estimated=False)
A list is filter[category][in]=novela-negra,poesia; a dict of operators, a range; {"null": True}, the missing values.
>>> books.get("7")
{'id': '7', 'title': 'La niebla de Portugalete', 'price': '18.50', 'rating': 4.6, 'year': 2025, 'category': 'novela-negra', 'author': {'id': '1'}, 'related': [{'id': '50'}], 'highlight': {'id': '1', 'href': '/books/7/reviews/1'}, '_etag': '"5a8458498e20a142"'}
>>> new = books.create({"title": "Faro apagado", "price": "9.90", "category": "poesia"}) # with Idempotency-Key
>>> new
{'title': 'Faro apagado', 'price': '9.90', 'category': 'poesia', 'id': '100', '_etag': '"96c91d2d169e2d3d"'}
>>> new = books.update(new["id"], {"price": "10.50"}, if_match=new)
>>> new["price"], new["_etag"]
('10.50', '"c177a9bd3abc3ad1"')
>>> books.delete(new["id"], if_match=new)
>>> books.update("7", {"price": "1.00"}, if_match='"stale"')
restep.errors.PreconditionFailed: 412 precondition_failed: Someone changed it: read it again before writing.
The first five never reach the server (local is True). The last ones come from it.
for call in [lambda: books.list(filter={"author": "x"}), lambda: books.list(sort="-category"),
lambda: books.list(limit=51), lambda: books.list(filter={"category": "comic"}),
lambda: books.list(filter={"year": {"ge": "two thousand"}}),
lambda: books.get("999"), lambda: books.create({"title": "No price"})]:
try:
call()
except restep.RestepError as e:
print(type(e).__name__, e.status, e.code, e.parameter, e.local)
UnsupportedParameter 400 unsupported_parameter filter[author] True
UnsupportedParameter 400 unsupported_parameter sort True
InvalidParameter 400 invalid_parameter limit True
InvalidParameter 400 invalid_parameter filter[category] True
InvalidParameter 400 invalid_parameter filter[year][ge] True
NotFound 404 not_found None False
Invalid 422 invalid None False
The 422 carries the details in e.errors: [{'pointer': '/price', 'code': 'required', 'detail': 'price is required.'}]. With validate=False the first one goes to the server and comes back as the same class, with the same parameter:
UnsupportedParameter 400 unsupported_parameter filter[author] False | This resource does not support filter[author].
import asyncio, restep.aio
async def main():
async with await restep.aio.connect("http://localhost:18080/") as api:
page = await api["books"].list(limit=3, sort="title")
print([b["title"] for b in page.items])
async for book in api["books"].iter(limit=2):
...
book = await api["books"].get("7")
book = await api["books"].update("7", {"price": "19.00"}, if_match=book)
asyncio.run(main())
['Bajo la niebla', 'Cartografía del ruido', 'Cuaderno de faros']
restep.connect(url, token=None, language=None, *, …)| Argument | Default | What it does |
|---|---|---|
token | None | Authorization: Bearer, only to the API’s origin |
language | None | Accept-Language for the API’s texts: errors and descriptions (5.6) |
headers | None | Extra headers on every request |
validate | True | Check parameters, methods and actions against discovery before sending |
retries | 0 | Retries on 429, always, and on 503 when repeating cannot duplicate the effect: GET, PATCH, DELETE, a POST with Idempotency-Key or with an id chosen by the client (5.7), an idempotent action. Also on 409 request_in_progress, with the same key; never on 409 conflict. Waits for Retry-After, or 0.5 s, 1 s, 2 s… |
max_retry_wait | 60 | If Retry-After asks for longer, it does not retry |
timeout | 30 | Seconds per request |
restep.aio.connect takes the same arguments plus client: any object shaped like httpx.AsyncClient. Close it with await api.aclose() or use async with.
Api| Member | What it is |
|---|---|
api["books"], api.collections | A declared collection; all of them, by name |
api.collection(name, path=None) | A collection, or one the API does not declare, at path |
api.singletons | The declared singletons, by name (5.9). One with a template in path or with parent is ignored |
api.profiles, api.extensions | frozensets of what the API announces |
api.version, api.pre_release | The declared restep, and its draft.N or rc.N suffix, or None for a published version (1.1). restep.parse_version("1.0-draft.6") gives (1, 0, "draft.6") |
api.usable(part) | Whether an experimental part (1.2) is announced under a version whose text the client implements |
api.deprecations | The deprecation notices, with announced and sunset (5.5). One with an unknown kind is left out |
api.discovery, api.root | The discovery document (None without one) and the root URL |
api.status() | True or False from the declared status resource (4.4); LookupError if discovery declares none |
Collection| Method | What it does |
|---|---|
list(*, filter, named, sort, fields, include, limit, count) | One Page: items, next, total, raw and next_page(), which follows next as it is and returns None at the end. A page iterates over its items |
iter(*, filter, named, sort, fields, include, limit) | Every item, page after page; limit is the page size |
count(*, filter, named) | A Total: an int with estimated |
get(id, *, fields, include) | One item, with _etag |
create(data, *, idempotency_key=AUTO) | POST. AUTO makes a key when the API announces writes; a string uses yours; None, none. An id in data only where id_from lets the client choose it (5.1) |
update(id, patch, *, if_match=None) | PATCH with application/merge-patch+json; returns the whole item |
delete(id, *, if_match=None) | DELETE |
action(id, name, data=None, *, idempotency_key=AUTO) | A declared action (11.1): on an item with its id, on the collection with None. Non-idempotent actions get a key; a "method": "GET" action goes by GET |
at(**vars) | A subcollection with its URI template filled in: api["reviews"].at(book_id="7") |
ref(id) | The relationship object for an item: {"id": "3", "href": "/books/7/reviews/3"}. An item of a subcollection is linked by href (5.1) |
id_from, collation(field) | Who picks the id ("server", "client", "either"), and whether a text field compares as "codepoint" or "server" (6.1) |
inherited(item, field) | Where an inherited value comes from: "own", {"href": …}, "default" or "hidden", which is also what an unknown from gives (11.6). restep.ExperimentalNotUsable if the API does not announce inherit under a version the client implements |
A Singleton (api.singletons["shop"]) has get(*, fields), with _etag, and update(patch, *, if_match).
named takes the named filters (6.1), without operators: books.list(named={"featured": True, "search": "niebla"}). sort, fields and include take a comma string or a list. In filter, a plain value is equality, a list is in, a dict holds operators ({"price": {"ge": 10, "le": "20"}}), and a language map is filtered with its tag ({"name.es-mx": "Separador"}). None is an error: for no value, {"null": True}.
UnsupportedParameter: a profile the API does not announce, an undeclared filter field, operator, sort key or relation, an include deeper than include_depth, count on a collection that does not declare it.InvalidParameter: a value that does not fit its type, an enum value outside values, an empty in list or one with commas, a limit outside 1..max_limit, a fields name missing from an inline item schema, a path into a language map (name.es).MethodNotAllowed: a method missing from methods or item_methods. NotFound: an undeclared action. Invalid: a create with id where the server picks it, or where id_from has a value it does not know, or without one where it is "client". BadRequest: an explicit idempotency_key without credentials where the server declares "anonymous": false.type, an unknown count, an action with an unknown on or method.RestepError, then ClientError (4xx) and ServerError (5xx), then one class per code of 5.4: BadRequest (with InvalidParameter, UnsupportedParameter, IdempotencyKeyRequired), Unauthenticated, Forbidden, NotFound, MethodNotAllowed, NotAcceptable, Conflict, RequestInProgress (the other 409, not a child of Conflict, because it can be repeated), Gone (with StateExpired, Retired), PreconditionFailed, ContentTooLarge, UriTooLong, UnsupportedMediaType, Invalid, IdempotencyMismatch, NotExecuted, PreconditionRequired, RateLimited, Internal, ServerNotImplemented, Unavailable. An unknown code falls back to its status: that status’s class when it has only one, ClientError or ServerError otherwise. An unknown reason changes nothing: the exception is its code’s, with the reason in e.reason. Outside this tree, UnsupportedVersion (a ValueError) and ExperimentalNotUsable (a LookupError).
Each has status, code, detail, parameter, errors, reason, problem, headers, local and retry_after. Unauthenticated adds resource_metadata, from the challenge; MethodNotAllowed, allow.
It does not get tokens: that is your OAuth library’s job. It helps find where to ask (11.5):
>>> restep.oauth_metadata_url("https://example.com/api/")
'https://example.com/.well-known/oauth-protected-resource/api/'
>>> meta = restep.oauth_metadata("https://example.com/api/") # checks that resource is the root
create and update schemas: the server does, with its 422 invalid. Nor does it fetch linked schemas; the fields check only uses an inline item schema.sync (:changes, events), batch, filter-expr or query-method, no Prefer: return=minimal, and no relationships of a singleton beyond reading them. For an offline replica there is restep-sync, in JavaScript.unsupported_parameter or a 405 for something its copy declares, nor revalidate it with its Cache-Control. Nor does it do anything with the cache profile (8) beyond copying the ETag into _etag.dict[str, Any]: values are not converted back to Python types, and there are no types per collection.language says. Server errors keep the server’s text.Browse any Restep API from this site: query forms built from discovery, writes, actions, errors explained and the curl for every request.
A command line client that learns the API from discovery: get, create, update, delete, actions, every page, CSV, and completion in zsh and bash.
An offline-first client: a local replica kept up to date incrementally, writes that queue while offline, and conflicts resolved your way.