Getting Started

This part of the documentation covers how to start using the Image Intelligence API. The first thing you need to do is to sign up for an account and create an application. Doing this will give you 2 key things:

clientId='Gjc0Xek5EjmwhDFaIN9bl02r0GniEkdF'
clientSecret='fqmWQRJyZTceabNo-xMbTKlLsZeyAi-LLgCkA_p3SNrWHKMydsgAhjJiUwX-AMv5'

If you want a refresher on how to obtain these secrets, you can read up on it here. Now that you have a clientId and clientSecret, the next step is to generate an accessToken:

import requests

endpoint = 'https://api.imageintelligence.com/v2/oauth/token'
payload = {
  'clientId': clientId,
  'clientSecret': clientSecret,
}

response = requests.post(endpoint, data=json.dumps(payload)).json()
access_token = response['accessToken']

Note that the accessToken has a 24hr expiration timer. This means a new accessToken will have to be generated again when it expires. To avoid having to make multiple requests (/oauth/token and /detect for example), cache the accessToken.

import time
import requests


class ImageIntelligenceApiToken:
    AUTH_TOKEN_EXPIRE_BUFFER = 1000 * 30  # 0.5 minutes in milliseconds

    def __init__(self, **kwargs):
        self.token = kwargs['accessToken']
        self.expires_at = kwargs['expiresAt']
        self.issued_at = kwargs['issuedAt']
        self.org_name = kwargs['orgName']
        self.app_name = kwargs['appName']
        self.scope = kwargs['scope']

    @property
    def expired(self):
        return (time.time() * 1000) >= (self.expires_at - self.AUTH_TOKEN_EXPIRE_BUFFER)


class ImageIntelligenceApi:
    MAX_POLL_ATTEMPTS = 5

    def __init__(self, client_id, client_secret, base_endpoint=BASE_ENDPOINT, token=None):
        self.client_id = client_id
        self.client_secret = client_secret
        self.base_endpoint = base_endpoint
        self.token = token

    def get_token(self, client_id, client_secret, base_endpoint=BASE_ENDPOINT):
        endpoint = base_endpoint + OAUTH_PATH
        payload = {'clientId': client_id, 'clientSecret': client_secret}

        response = requests.post(endpoint, data=json.dumps(payload))
        if response.status_code == HTTPStatus.UNAUTHORIZED:
            raise InvalidClientCredentialsError()
        if response.status_code != HTTPStatus.OK:
            raise UnknownAuthenticationError()
        return ImageIntelligenceApiToken(**response.json())

    def refresh_token(self):
        if self.token and not self.token.expired:
            return self.token
        self.token = get_token(
            self.client_id,
            self.client_secret,
            base_endpoint=self.base_endpoint,
        )
        return self.token

    def api_request(self, method, endpoint, token, payload=None, headers=None):
        payload = payload or {}
        headers = headers or {}

        headers['Authorization'] = 'Bearer %s' % token.token
        response = method(endpoint, data=json.dumps(payload), headers=headers)

        if response.status_code != HTTPStatus.OK:
            raise ApiRequestError('(%s) %s' % (response.status_code, response.text))
        return response.json()

    def detect(self, images, classes, webhook_url=None, feed_id=None, custom_id=None):
        return self.api_request(
            requests.post,
            self.base_endpoint + '/detect',
            self.refresh_token(),
            payload={
                'images': images,
                'classes': classes,
                'webhookUrl': webhook_url,
                'feedId': feed_id,
                'customId': custom_id,
            },
        )

In the example above, we've wrapped the accessToken into a ImageIntelligenceApiToken class. The important part is:

@property
def expired(self):
    return (time.time() * 1000) >= (self.expires_at - self.AUTH_TOKEN_EXPIRE_BUFFER)

To determine if a token is expired, you can compare the expires_at field with the current time + buffer (as to be safe - avoid 401 errors). Note that /oauth/token is stateless. If a new request is made to /oauth/token and the previously issued accessToken has yet to expire, a new token will be returned regardless.

Now that you have an accessToken, you can start making authenticated requests!

from pprint import pprint

client = ImageIntelligenceApi(client_id, client_secret)
pprint(client.detect([
  {'url': 'http://example.com/image-1.jpg' },
  {'url': 'http://example.com/image-2.jpg' },
  {'url': 'http://example.com/image-3.jpg' },
], [
  {'class': 'person', 'hitl': 'NEVER'},
]))

You can read more about other endpoints in our API reference or for a more complete example, check out our slackbot.