- A method for building GraphQL integrations has been introduced.
- It follows the "Clientele" pattern of the standard
APIClient.
Query example:
@client.query('''
query($owner: String!, $name: String!) {
repository(owner: $owner, name: $name) {
name
stargazerCount
}
}
''')
def get_repo(owner: str, name: str, result: RepositoryData) -> Repository:
return result.repositoryMutation example:
@client.mutation('''
mutation($title: String!) {
createIssue(input: {title: $title}) {
issue { id title }
}
}
''')
def create_issue(title: str, result: IssueData) -> Issue:
return result.createIssue.issue- Dropped
scaffold-apicommand - Dropped
generate-basiccommand - Drop
httpx_clientfromAPIClient - Drop
httpx_async_clientfromAPIClient
This release includes testing tools to make API integration testing easier.
- Added
ResponseFactorytoclientele.testingfor quick response fixtures. - Create common HTTP responses easily:
ok(),created(),not_found(),bad_request(),internal_server_error(), and more.
- Added
NetworkErrorFactoryfactory toclientele.testingfor simulating network-level failures. - Simulate common network errors like
timeout(),connection_refused(),connection_reset(), anddns_failure(). FakeHTTPBackendnow supportsqueue_error()to queue errors for specific paths.
- Fix streaming responses to truly yield instead of consuming the full response.
- Introduces new http_backend methods for handling streaming however the backend chooses.
- Built-in
retries.retrydecorator for handling retry logic. - This is built on top of
stamina- a popular and reliable retry package. - The retry logic is customised to suit Clientele's exception handling.
from clientele import api, retries
client = api.APIClient(api.BaseConfig(base_url="https://httpbin.org/"))
@retries.retry(attempts=3)
@client.get("/status/{status_code}")
def get_status(status_code: int, result: dict) -> dict:
return result- We have drastically improved the testing support for Clientele.
- The
FakeHTTPBackendis now designed for testing. - The
queue_responsemethod now takes ahttp.Responseobject as well as the path. - The new
configure_client_for_testingfunction accepts an existing client and then returns it with a new testing backend.
from clientele.testing import configure_client_for_testing
from clientele import http
from my_api_client import client, my_function
def my_test():
# Swap normal backend for a Fake HTTP backend
fake_backend: http.FakeHTTPBackend = configure_client_for_testing(my_api_client.client)
# Configure HTTP responses
fake_backend.queue_response(
path="/users",
response_obj=Response(
status_code=201,
content=b'{"id": 10, "name": "Bob"}',
headers={"content-type": "application/json"},
),
)
# Call function as normal, but it now calls the fake backend
response = my_function()- While it is a cool feature, it distracts from the purpose of Clientele, so it is being removed.
- Add
configuremethod toAPIClient- enabling reconfiguration of clients. Thank you Christian Assing for the contribution.
- Added optional request/response logging to
APIClientvia theloggerparameter inBaseConfig. Logs include method, URL, status code, and elapsed time in seconds. - Uses a
LoggerProtocol with@runtime_checkablefor flexibility. - Thank you Matías Giménez for the contribution.
- A new command
start-apihas been introduced. - The new command will replace
scaffold-apiandgenerate-basicin 2.0.0 - Currently it behaves as an alias for both.
- If not url or file is provided, will call
generate-basic, otherwise it callsscaffold-api.
Start a basic client with one command:
uvx clientele start-api -o /path/to/my_client- Dropped the
generateandgenerate-classcommands from the CLI.
- Support for OpenAPI discriminated unions (
oneOf+discriminator). Schemas with discriminators now generate proper Pydantic discriminated unions usingtyping.Annotated[..., pydantic.Field(discriminator="...")].
- Clientele now supports configurable HTTP backends.
- If you want to use
aiohttp,reqwestsorniquestsyou can write anHTTPBackendso Clientele can support it. - Clientele ships with a default
HttpxHTTPBackendthat will be used if no other is configured. - Introduces a new
clientele.http.Responsewrapper for generic handling of responses. - The
response_parsercallbacks now take the genericclientele.http.Responseinstead ofhttpx.Response. - Introduces a new
FakeHTTPBackendthat can be used for testing.
- An optional approach for making requests with Clientele is now available.
- This approach does not enforce the decorator pattern.
- But still offers smart data hydration and response mapping.
- Support for both async and sync.
cache_backendcan now be set in theBaseConfig, and will be used if it is not None. This saves you having to annotate the cache backend repeatedly in decorators.
- Clientele now supports streaming responses via Server Sent Events.
- Streaming is controlled via the
streaming_response=Trueparameter on all HTTP method decorators (get,post,put,patch,delete). - Clientele will attempt to hydrate the response into the correct type supplied by the
resultparameter. response_parsercallbacks are supported and will be applied to each streamed item.response_mapis not currently supported for streaming endpoints.
from typing import AsyncIterator
from pydantic import BaseModel
from clientele import api
client = api.APIClient(base_url="http://localhost:8000")
class Event(BaseModel):
text: str
@client.get("/events", streaming_response=True)
async def stream_events(*, result: AsyncIterator[Event]) -> AsyncIterator[Event]:
return resultUsage:
async for event in await stream_events():
print(event.text)- A mypy plugin has been added that correctly handles Clientele. You will no longer see issues for the
resultandresponsearguments. Big shout out to Christian Assing for this contribution.
- The
scaffold-apicommand now outputs a standardpyproject.tomlinto the client directory. It will not be overwritten on subsequent regenerations. - Big code refactor - reorganising the
requestpreparation and type handling into separate files.
- Introduce
cache.memoizedecorator for sensible, http-specific caching of HTTP get requests. - Add documentation covering common approaches to handling retry logic.
- A tiny fix with error handling and using
response_parserwith plain types.
- Fix
scaffold-apigenerating post/put/patch/delete methods with a,,when dealing with optional args. Contributor: @peterHoburg.
- Correct
--regenand--asyncioto be boolean flags inscaffold-apicommand. Contributor: @peterHoburg. - Properly support
nullfield foranyOfschemas in OpenAPI schema generation. They now produceNonecorrectly.
- You can now pass
TypedDictinstances for thedataparameter onpost,put,patchanddeletemethods. - Decorated functions now accept a
response_parsercallback that will handle the response parsing. Use this to customise theresultvalue that is sent back to the function.
- Clientele API is a decorator-driven http client that can create elegant API integrations.
- Clientele API is considered a beta project for this release. It is an evolving idea that has been tested thoroughly and it works well in ideal conditions. Small changes to the API and usage may occur over time as we encounter unexpected scenarios.
- The
scaffold-apicommand will produce scaffolding from an OpenAPI schema and uses the new clientele api.
- The
explorecommand has been updated to support clients that use the clientele api pattern.
- New documentation added to cover Clientele API.
- Documentation sections have been reorganised to reflect the key features of Clientele.
- When clientele API reaches maturity, support for the current "barebones" style of OpenAPI scaffolders will be deprecated.
- This will be marked as the
2.0.0release.
- Print operation information in explorer by typing the name of the operation without parenthesis. Prints information such as the docstring, return type, and input arguments.
- Schema inspection in explore REPL has been improved. Typing a schema name without parentheses now displays the schema's docstring and fields instead of the verbose inherited Pydantic BaseModel documentation.
- Config objects now handle correctly in explore REPL. Supports old style config functions and the new style classes
- Correct package installation dependencies.
Version 1.0.0 represents 12 months of work, planning, testing and using clientele with real APIs. It has major new features and some breaking changes. I recommend completely deleting your previous clients and rebuilding to ensure a smooth rollout.
For most of this year I've been constrained by a lack of time to build the features I have planned. With the assistance of supervised agents I have been able to build out most of what I needed, and then spent time correcting and improving the agent's code to be functionally correct.
The productivity boost has been immense and has helped me to realise the goals and ambitions I have for this project.
- 🆕 Explorer CLI: Use
clientele exploreto use a REPL and discover APIs interactively, even without writing any code. - ⚙️ Rebuilt configuration:
config.pyhas been re-engineered to use pydantic settings. - 📜 Rebuilt parser - parsing OpenAPI schema into python objects is now handled entirely by Cicerone, our own OpenAPI parser that was built to meet our unique needs.
- Clientele now specifically offers 100% support for all major Python API frameworks: FastAPI, Django REST Framework, and Django-Ninja.
- Clientele is now tested and proven to generate clients for 2000+ openapi schemas as part of our CI. It runs weekly and we use it to ensure broad capability with all OpenAPI services.
- Fixed function parameter ordering (required parameters before optional ones).
- Nullable fields properly handled (OpenAPI 3.0
nullable: trueand OpenAPI 3.1 array type notation) - Fixed: Array responses without a
titlefield now correctly generate type aliases instead of wrapper classes with atestproperty. - Fixed: Responses with no content (e.g., 204 No Content) are now properly included in the status code map with
Noneas the response type. - Correctly handle reserved python keywords for schema model properties (i.e.
type,nextetc). - New: Extended httpx configuration options in generated clients - timeout, follow_redirects, verify_ssl, http2, and max_redirects are now configurable.
- Removed the
validatecommand from the CLI. - Replaced
openapi-coredependency withcicerone==0.3.0for OpenAPI schema parsing and introspection. This change provides faster, more minimal, and fully typed OpenAPI schema handling. - New: Support for OpenAPI
deprecatedfield - operations marked as deprecated will include deprecation warnings in generated docstrings. - New: Support for OpenAPI
descriptionfield - operation descriptions are now included in generated function docstrings for better documentation. - Clientele is 100% typed, including the generated code, and verified using ty instead of mypy.
- Updated all dependencies to their latest stable versions.
- New: Class-based client generator! Use
clientele generate-classto generate a client with aClientclass and methods instead of standalone functions. - Class-based clients support both sync and async modes with
--asyncio tflag. - Class-based clients are perfect for object-oriented codebases and when you need to mock the client for testing.
- New: Dynamic configuration for class-based clients! Class-based clients now accept a
Configobject in their constructor, allowing you to create multiple clients with different configurations on the fly. - The
config.pyfile in class-based clients now generates aConfigclass instead of standalone functions, enabling runtime configuration changes. - You can now instantiate clients with custom configuration:
client = Client(config=Config(api_base_url="https://api.example.com", bearer_token="my-token")). - This addresses issues #42 and #49, enabling dynamic auth tokens and multiple clients with different configurations.
- Updated documentation with comprehensive examples of class-based client usage.
- Added
generate-classcommand to CLI with full feature parity to the standardgeneratecommand. - Add ABC (Abstract Base Class) pattern to generators with a
Generatorbase class that all generators inherit from. - Refactored all imports to import modules.
- Changed: Generated code is now auto-formatted with Ruff instead of Black.
- Breaking change for class-based clients: The
config.pyfile structure has changed from functions to a class. Existing generated clients will need to be regenerated with--regen t. - Fixed: OpenAPI
numbertype now correctly maps to Pythonfloatinstead ofint. Theintegertype continues to map toint, andnumberwithformat: "decimal"continues to map todecimal.Decimal. This addresses issue #40. - New: Python 3.13 and Python 3.14 support! Clientele and all generated clients now officially support Python 3.10, 3.11, 3.12, 3.13, and 3.14.
- Python 3.9 support has been dropped. If you need Python 3.9 support, please use version 0.9.0 or earlier.
- Support
patchmethods - Fix
config.pyfile being overwritten when generating new clients
- Fix bug with headers assignment
- Improved json support
- Function parameters no longer format to snake_case to maintain consistency with the OpenAPI schema.
- Improved support for Async clients which prevents a weird bug when running more than one event loop. Based on the suggestions from this httpx issue.
- We now use
ruff formatfor coding formatting (not the client output). Decimalsupport now extends to Decimal input values.- Input and Output schemas will now have properties that directly match those provided by the OpenAPI schema. This fixes a bug where previously, the snake-case formatting did not match up with what the API expected to send or receive.
- Support for
Decimaltypes.
- Updated all files to use the templates engine.
- Generator files have been reorganised in clientele to support future templates.
constants.pyhas been renamed toconfig.pyto better reflect how it is used. It is not generated from a template like the other files.- If you are using Python 3.10 or later, the
typing.Unionstypes will generate as the short hand|instead. - To regenerate a client (and to prevent accidental overrides) you must now pass
--regen tor-r tto thegeneratecommand. This is automatically added to the line inMANIFEST.mdto help. - Clientele will now automatically run black code formatter once a client is generated or regenerated.
- Clientele will now generate absolute paths to refer to adjacent files in the generated client, instead of relative paths. This assumes you are running the
clientelecommand in the root directory of your project. - A lot of documentation and docs strings updates so that code in the generated client is easier to understand.
- Improved the utility for snake-casing enum keys. Tests added for the functions.
- Python 3.12 support.
- Add a "basic" client using the command
generate-basic. This can be used to keep a consistent file structure for an API that does not use OpenAPI.
- Packaged application installs in the correct location. Resolving #6
- Updated pyproject.toml to include a better selection of links.
- Ignore optional URL query parameters if they are
None.
- Added
from __future__ import annotationsin files to help with typing evaluation. - Update to use pydantic 2.4.
- A bunch of documentation and readme updates.
- Small wording and grammar fixes.
- Significantly improved handling for response schemas. Responses from API endpoints now look at the HTTP status code to pick the correct response schema to generate from the HTTP json data. When regenerating, you will notice a bit more logic generated in the
http.pyfile to handle this. - Significantly improved coverage of exceptions raised when trying to generate response schemas.
- Response types for a class are now sorted.
- Fixed a bug where
putmethods did not generate input data correctly.
- Fix pathing for
constants.py- thanks to @matthewknight for the contribution! - Added
CONTRIBUTORS.md
- Support for HTTP PUT methods
- Headers objects use
exclude_unsetto avoid passingNonevalues as headers, which httpx does not support.
Additionally, an async test client is now included in the test suite. It has identical tests to the standard one but uses the async client instead.
- Paths are resolved correctly when generating clients in nested directories.
additional_headers()is now applied to every client, allowing you to set up headers for all requests made by your client.- When the client cannot match an HTTP response to a return type for the function it will now raise an
http.APIException. This object will have theresponseattached to it for inspection by the developer. MANIFESTis now renamed toMANIFEST.mdand will include install information for Clientele, as well as information on the command used to generate the client.
Examples and documentation now includes a very complex example schema built using FastAPI that offers the following variations:
- Simple request / response (no input just an output)
- A request with a URL/Path parameter.
- Models with
int,str,list,dict, references to other models, enums, andlists of other models and enums. - A request with query parameters.
- A response model that has optional parameters.
- An HTTP POST request that takes an input model.
- An HTTP POST request that takes path parameters and also an input model.
- An HTTP GET request that requires an HTTP header, and returns it.
- An HTTP GET endpoint that returns the HTTP bearer authorization token (also makes clientele generate the http authentication for this schema).
A huge test suite has been added to the CI pipeline for this project using a copy of the generated client from the schema above.
Enumsnow inherit fromstras well so that they serialize to JSON properly. See this little nugget.
- Correctly use
model_rebuildfor complex schemas where there are nested schemas, his may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema. - Do not raise for status, instead attempt to return the response if it cannot match a response type.
- Correctly generate lists of nested schema classes
- Correctly build response schemas that are emphemeral (such as when they just return an array of other schemas, or when they have no $ref).
- Change install suggestion to use pipx as it works best as a global CLI tool.
- Improved support for OpenAPI 3.0.3 schemas (a test version is available in the example_openapi_specs directory).
validatecommand for validating an OpenAPI schema will work with clientele.versioncommand for showing the current version of clientele.- Supports HTTP DELETE methods.
- Big refactor of how methods are generated to reduce duplicate code.
- Support optional header parameters in all request functions (where they are required).
- Very simple Oauth2 support - if it is discovered will set up HTTP Bearer auth for you.
- Uses
dictandlistinstead oftyping.Dictandtyping.Listrespectively. - Improved schema generation when schemas have $ref to other models.
- Minor changes to function name generation to make it more consistent.
- Optional parameters in schemas are working properly.
- Fixes a bug when generating HTTP Authentication schema.
- Fixes a bug when generating input classes for post functions, when the input schema doesn't exist yet.
- Generates pythonic function names in clients now, always (like
lower_case_snake_case).
- Now generates a
MANIFESTfile with information about the build versions - Added a
constants.pyfile to the output if one does not exist yet, which can be used to store values that you do not want to change between subsequent re-generations of the clientele client, such as the API base url. - Authentication patterns now use
constants.pyfor constants values. - Removed
ipythonfrom package dependencies and moved to dev dependencies. - Documentation! https://phalt.github.io/clientele/
- Improved CLI output
- Code organisation is now sensible and not just one giant file
- Now supports an openapi spec generated from a dotnet project (
Microsoft.OpenApi.Models) - async client support fully working
- HTTP Bearer support
- HTTP Basic support
- Initial version
- Mostly works with a simple FastAPI generated spec (3.0.2)
- Works with Twilio's spec (see example_openapi_specs/ directory) (3.0.1)
- Almost works with stripes