Skip to main content

The official Python library for the Finch API

Project description

Finch Python API library

PyPI version

The Finch Python library provides convenient access to the Finch REST API from any Python 3.7+ application. The library includes type definitions for all request params and response fields, and offers both synchronous and asynchronous clients powered by httpx.

Documentation

The API documentation can be found in the Finch Documentation Center.

Installation

pip install finch-api

Usage

The full API of this library can be found in api.md.

from finch import Finch

client = Finch(
    access_token="My Access Token",
)

page = client.hris.directory.list()
print(page.page)

Async usage

Simply import AsyncFinch instead of Finch and use await with each API call:

import asyncio
from finch import AsyncFinch

client = AsyncFinch(
    access_token="My Access Token",
)


async def main() -> None:
    page = await client.hris.directory.list()
    print(page.page)


asyncio.run(main())

Functionality between the synchronous and asynchronous clients is otherwise identical.

Using types

Nested request parameters are TypedDicts. Responses are Pydantic models, which provide helper methods for things like:

  • Serializing back into JSON, model.model_dump_json(indent=2, exclude_unset=True)
  • Converting to a dictionary, model.model_dump(exclude_unset=True)

Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set python.analysis.typeCheckingMode to basic.

Pagination

List methods in the Finch API are paginated.

This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:

import finch

client = Finch()

all_directories = []
# Automatically fetches more pages as needed.
for directory in client.hris.directory.list():
    # Do something with directory here
    all_directories.append(directory)
print(all_directories)

Or, asynchronously:

import asyncio
import finch

client = AsyncFinch()


async def main() -> None:
    all_directories = []
    # Iterate through items across all pages, issuing requests as needed.
    async for directory in client.hris.directory.list():
        all_directories.append(directory)
    print(all_directories)


asyncio.run(main())

Alternatively, you can use the .has_next_page(), .next_page_info(), or .get_next_page() methods for more granular control working with pages:

first_page = await client.hris.directory.list()
if first_page.has_next_page():
    print(f"will fetch next page using these details: {first_page.next_page_info()}")
    next_page = await first_page.get_next_page()
    print(f"number of items we just fetched: {len(next_page.individuals)}")

# Remove `await` for non-async usage.

Or just work directly with the returned data:

first_page = await client.hris.directory.list()

print(
    f"the current start offset for this page: {first_page.paging.offset}"
)  # => "the current start offset for this page: 1"
for directory in first_page.individuals:
    print(directory.id)

# Remove `await` for non-async usage.

Nested params

Nested parameters are dictionaries, typed using TypedDict, for example:

from finch import Finch

client = Finch()

page = client.hris.directory.list()
print(page.page)

Webhook Verification

We provide helper methods for verifying that a webhook request came from Finch, and not a malicious third party.

You can use finch.webhooks.verify_signature(body: string, headers, secret?) -> None or finch.webhooks.unwrap(body: string, headers, secret?) -> Payload, both of which will raise an error if the signature is invalid.

Note that the "body" parameter must be the raw JSON string sent from the server (do not parse it first). The .unwrap() method can parse this JSON for you into a Payload object.

For example, in FastAPI:

@app.post('/my-webhook-handler')
async def handler(request: Request):
    body = await request.body()
    secret = os.environ['FINCH_WEBHOOK_SECRET']  # env var used by default; explicit here.
    payload = client.webhooks.unwrap(body, request.headers, secret)
    print(payload)

    return {'ok': True}

Handling errors

When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of finch.APIConnectionError is raised.

When the API returns a non-success status code (that is, 4xx or 5xx response), a subclass of finch.APIStatusError is raised, containing status_code and response properties.

All errors inherit from finch.APIError.

import finch
from finch import Finch

client = Finch()

try:
    client.hris.company.retrieve()
except finch.APIConnectionError as e:
    print("The server could not be reached")
    print(e.__cause__)  # an underlying Exception, likely raised within httpx.
except finch.RateLimitError as e:
    print("A 429 status code was received; we should back off a bit.")
except finch.APIStatusError as e:
    print("Another non-200-range status code was received")
    print(e.status_code)
    print(e.response)

Error codes are as followed:

Status Code Error Type
400 BadRequestError
401 AuthenticationError
403 PermissionDeniedError
404 NotFoundError
422 UnprocessableEntityError
429 RateLimitError
>=500 InternalServerError
N/A APIConnectionError

Retries

Certain errors are automatically retried 2 times by default, with a short exponential backoff. Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors are all retried by default.

You can use the max_retries option to configure or disable retry settings:

from finch import Finch

# Configure the default for all requests:
client = Finch(
    # default is 2
    max_retries=0,
)

# Or, configure per-request:
client.with_options(max_retries=5).hris.directory.list()

Timeouts

By default requests time out after 1 minute. You can configure this with a timeout option, which accepts a float or an httpx.Timeout object:

from finch import Finch

# Configure the default for all requests:
client = Finch(
    # default is 60s
    timeout=20.0,
)

# More granular control:
client = Finch(
    timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),
)

# Override per-request:
client.with_options(timeout=5 * 1000).hris.directory.list()

On timeout, an APITimeoutError is thrown.

Note that requests that time out are retried twice by default.

Default Headers

We automatically send the Finch-API-Version header set to 2020-09-17.

If you need to, you can override it by setting default headers per-request or on the client object.

Be aware that doing so may result in incorrect types and other unexpected or undefined behavior in the SDK.

from finch import Finch

client = Finch(
    default_headers={"Finch-API-Version": "My-Custom-Value"},
)

Advanced

Logging

We use the standard library logging module.

You can enable logging by setting the environment variable FINCH_LOG to debug.

$ export FINCH_LOG=debug

How to tell whether None means null or missing

In an API response, a field may be explicitly null, or missing entirely; in either case, its value is None in this library. You can differentiate the two cases with .model_fields_set:

if response.my_field is None:
  if 'my_field' not in response.model_fields_set:
    print('Got json like {}, without a "my_field" key present at all.')
  else:
    print('Got json like {"my_field": null}.')

Accessing raw response data (e.g. headers)

The "raw" Response object can be accessed by prefixing .with_raw_response. to any HTTP method call.

from finch import Finch

client = Finch()
response = client.hris.directory.with_raw_response.list()
print(response.headers.get('X-My-Header'))

directory = response.parse()  # get the object that `hris.directory.list()` would have returned
print(directory.id)

These methods return an APIResponse object.

Configuring the HTTP client

You can directly override the httpx client to customize it for your use case, including:

  • Support for proxies
  • Custom transports
  • Additional advanced functionality
import httpx
from finch import Finch

client = Finch(
    # Or use the `FINCH_BASE_URL` env var
    base_url="http://my.test.server.example.com:8083",
    http_client=httpx.Client(
        proxies="http://my.test.proxy.example.com",
        transport=httpx.HTTPTransport(local_address="0.0.0.0"),
    ),
)

Managing HTTP resources

By default the library closes underlying HTTP connections whenever the client is garbage collected. You can manually close the client using the .close() method if desired, or with a context manager that closes when exiting.

Versioning

This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:

  1. Changes that only affect static types, without breaking runtime behavior.
  2. Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals).
  3. Changes that we do not expect to impact the vast majority of users in practice.

We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.

We are keen for your feedback; please open an issue with questions, bugs, or suggestions.

Requirements

Python 3.7 or higher.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

finch_api-0.8.1.tar.gz (62.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

finch_api-0.8.1-py3-none-any.whl (102.0 kB view details)

Uploaded Python 3

File details

Details for the file finch_api-0.8.1.tar.gz.

File metadata

  • Download URL: finch_api-0.8.1.tar.gz
  • Upload date:
  • Size: 62.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.6

File hashes

Hashes for finch_api-0.8.1.tar.gz
Algorithm Hash digest
SHA256 997d1d9012df09bde9f959d0e89f2c457493772295e15684b3270a6835091502
MD5 9e2b91626c5ef7f42f08a736c757a620
BLAKE2b-256 08d3f8e45e48521e96d85f0ea01d8673679e5f304165feebde693bba8218ddbe

See more details on using hashes here.

File details

Details for the file finch_api-0.8.1-py3-none-any.whl.

File metadata

  • Download URL: finch_api-0.8.1-py3-none-any.whl
  • Upload date:
  • Size: 102.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.6

File hashes

Hashes for finch_api-0.8.1-py3-none-any.whl
Algorithm Hash digest
SHA256 4a2cdcec5a54a3bcb548c456587990d3fec48acbb9c9ec9e5f10c837e0b3de6f
MD5 50a887dcf6c2228990943c555679a847
BLAKE2b-256 043d506c48795386f28ebe96be7868a90ee6ccb102823928881356ace811e57b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page