Skip to content

Hustle/hustle-public-api-samples

Repository files navigation

Here we represent two ways of accessing the public api. One is for basic scripts with the requests library. The other is through a generated client library for accessing the Hustle Public API

Using requests to manually build out requests

The requests library for python is incredibly powerful and versatile and allows you to handle your own headers and such.

The samples for this live in the root directory under requests_samples. With requests, we build out the payloads, specify our method and url, and manually handle the response.

requests has docs on how to handle status codes at https://requests.readthedocs.io/en/latest/user/quickstart/#response-status-codes. In the example below (and most requests samples), we choose to throw when we receive a non-200 code.

import requests

base_url = 'https://api.hustle.com/v3'
access_token = ''

def get_access_token(client_id, client_secret):
    payload = {
        'client_id': client_id,
        'client_secret': client_secret,
        'grant_type': 'client_credentials'
    }

    request = requests.post(f'{base_url}/oauth/token', json=payload)
    request.raise_for_status()
    json = request.json()
    access_token = json['access_token']

You can then use the access token (which has a timeout of 1 hour) to access authenticated endpoints by manually setting the authorization header as Authorization: Bearer <token> like so:

def create_lead(phone_number: str, first_name: str, last_name: str, organization_id: str):
    payload = {
        'firstName': first_name,
        'lastName': last_name,
        'phoneNumber': phone_number,
        'organizationId': organization_id
    }
    headers = {'Authorization': f'Bearer {access_token}'}
    request = requests.post(
        f'{base_url}/leads',
        json=payload,
        headers=headers
    )
    request.raise_for_status()
    json = request.json()
    print(json)

One common pitfall is using data instead of json to pass payloads. Our api is built with nested objects in mind and the data parameter will destroy those nested objects as it's meant for form encoded data. This error usually shows up as [property]: Expected object, received array.

Autogenerated client using openapi-python-client

Inside of hustle_public_api_client is a client generated by https://github.com/openapi-generators/openapi-python-client. We expand on that generated client inside of the samples directory inside of that directory.

Usage

First, create a client so you can get your token:

from hustle_public_api_client import Client
from hustle_public_api_client.api.access_token import post_oauth_token
from hustle_public_api_client.models import PostOauthTokenBody

client = Client(base_url="https://api.hustle.com/v3")
credentials: PostOauthTokenBody = PostOauthTokenBody.from_dict({
            'client_id': self.client_id_stored,
            'client_secret': self.client_secret_stored,
            'grant_type': 'client_credentials',
        })
token_response = post_oauth_token.sync_detailed(client=unauth_client, body=credentials)
if token.status_code != 200:
    raise Exception('Credentials not valid')
token = token_response.parsed.access_token

Every endpoint you're going to hit will require authentication, use AuthenticatedClient once you have your token:

from hustle_public_api_client import AuthenticatedClient

client = AuthenticatedClient(base_url="https://api.example.com", token=token)

Now call your endpoint and use your models:

from hustle_public_api_client.models import Organization
from hustle_public_api_client.api.organizations import get_organizations
from hustle_public_api_client.models.get_organizations_response_200 import GetOrganizationsResponse200
from hustle_public_api_client.types import Response

with client as client:
    my_data: GetOrganizationsResponse200 = get_organizations.sync(client=client)
    organization: [Organization] = my_data.items
    # or if you need more info (e.g. status_code)
    response: Response[GetOrganizationsResponse200] = get_organizations.sync_detailed(client=client)
    organization: [Organization] = response.parsed.items

Or do the same thing with an async version:

from hustle_public_api_client.models import Organization
from hustle_public_api_client.api.organizations import get_organizations
from hustle_public_api_client.models.get_organizations_response_200 import GetOrganizationsResponse200
from hustle_public_api_client.types import Response

async with client as client:
    my_data: GetOrganizationsResponse200 = get_organizations.asyncio(client=client)
    organization: [Organization] = my_data.items
    # or if you need more info (e.g. status_code)
    response: Response[GetOrganizationsResponse200] = get_organizations.asyncio_detailed(client=client)
    organization: [Organization] = response.parsed.items

Things to know:

  1. Every path/method combo in the openapi spec becomes a Python module with four functions:

    1. sync: Blocking request that returns parsed data (if successful) or None
    2. sync_detailed: Blocking request that always returns a Request, optionally with parsed set if the request was successful.
    3. asyncio: Like sync but async instead of blocking
    4. asyncio_detailed: Like sync_detailed but async instead of blocking
  2. All path/query params, and bodies become method arguments.

  3. If your endpoint had any tags on it, the first tag will be used as a module name for the function (my_tag above)

  4. Any endpoint which did not have a tag will be in hustle_public_api_client.api.default

Advanced customizations

There are more settings on the generated Client class which let you control more runtime behavior, check out the docstring on that class for more info. You can also customize the underlying httpx.Client or httpx.AsyncClient (depending on your use-case):

from hustle_public_api_client import Client

def log_request(request):
    print(f"Request event hook: {request.method} {request.url} - Waiting for response")

def log_response(response):
    request = response.request
    print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}")

client = Client(
    base_url="https://api.example.com",
    httpx_args={"event_hooks": {"request": [log_request], "response": [log_response]}},
)

# Or get the underlying httpx client to modify directly with client.get_httpx_client() or client.get_async_httpx_client()

You can even set the httpx client directly, but beware that this will override any existing settings (e.g., base_url):

import httpx
from hustle_public_api_client import Client

client = Client(
    base_url="https://api.example.com",
)
# Note that base_url needs to be re-set, as would any shared cookies, headers, etc.
client.set_httpx_client(httpx.Client(base_url="https://api.example.com", proxies="http://localhost:8030"))

Building this package

This project uses Poetry to manage dependencies and packaging. Here are the basics:

If you want to install this client into another project then:

  1. If that project is using Poetry, you can simply do poetry add <path-to-this-client> from that project
  2. If that project is not using Poetry:
    1. Build a wheel with poetry build -f wheel
    2. Install that wheel from the other project pip install <path-to-wheel>

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages