Skip to main content

Authentication

All requests to the AlphaSense Agent API must be authenticated using an OAuth2 password grant flow. This page covers how to obtain an access token, manage token lifecycle, and integrate authentication into your application.

Overview

The authentication flow is a single POST request to the AlphaSense authorization endpoint. You supply your API key, client credentials, and user credentials; the server returns a time-limited access token that you attach to every subsequent API call as a Bearer token.

Auth endpoint:

POST https://api.alpha-sense.com/auth

Request Parameters

The request requires a combination of header and body parameters. The body must be sent as application/x-www-form-urlencoded.

ParameterTypeLocationRequiredDescription
x-api-keystringHeaderYesYour AlphaSense API key. Identifies your registered application.
grant_typestringBodyYesMust always be "password".
usernamestringBodyYesThe email address associated with your AlphaSense account.
passwordstringBodyYesThe password for your AlphaSense account.
client_idstringBodyYesThe OAuth2 client ID issued to your application.
client_secretstringBodyYesThe OAuth2 client secret issued to your application.
Credential Security Never hard-code credentials in source files, commit them to version

control, or expose them in client-side code. Always load credentials from environment variables or a secrets manager. :::

Token Response

A successful authentication request returns a JSON object containing your access token.

{
"access_token": "123456-1234-12...",
"token_type": "Bearer",
"expires_in": 86400
}
FieldTypeDescription
access_tokenstringThe Bearer token to include in the Authorization header of all subsequent API requests.
token_typestringAlways "Bearer".
expires_inintegerToken lifetime in seconds. The default is 86400 (24 hours).

Using the Token

Attach the token to every API request in the Authorization header:

Authorization: Bearer <access_token>

Token Expiration and Refresh

Access tokens are valid for 24 hours from the time of issuance. The AlphaSense auth endpoint does not issue refresh tokens for the password grant flow. When your token expires, you must re-authenticate by repeating the full authentication request described above.

Recommended patterns:

  • Cache the token along with its expiration timestamp. Before each API call, check whether the token is still valid.
  • Handle 401 responses gracefully. If an API call returns 401 Unauthorized, re-authenticate and retry the request.
  • Avoid authenticating on every request. The token is valid for 24 hours, so there is no need to request a new one for each call.

Code Examples

The following examples read all credentials from environment variables. Set these before running:

export ALPHASENSE_API_KEY="your-api-key"
export ALPHASENSE_CLIENT_ID="your-client-id"
export ALPHASENSE_CLIENT_SECRET="your-client-secret"
export ALPHASENSE_EMAIL="your-email@example.com"
export ALPHASENSE_PASSWORD="your-password"

Full Authentication

import os
import requests

def get_access_token() -> str:
"""Authenticate with the AlphaSense API and return an access token."""
url = "https://api.alpha-sense.com/auth"

headers = {
"x-api-key": os.environ["ALPHASENSE_API_KEY"],
"Content-Type": "application/x-www-form-urlencoded",
}

payload = {
"grant_type": "password",
"username": os.environ["ALPHASENSE_EMAIL"],
"password": os.environ["ALPHASENSE_PASSWORD"],
"client_id": os.environ["ALPHASENSE_CLIENT_ID"],
"client_secret": os.environ["ALPHASENSE_CLIENT_SECRET"],
}

response = requests.post(url, headers=headers, data=payload)
response.raise_for_status()

token_data = response.json()
return token_data["access_token"]


if __name__ == "__main__":
token = get_access_token()
print(f"Token acquired (expires in 24 hours)")
# Use the token in subsequent requests:
# headers = {"Authorization": f"Bearer {token}"}

Token Caching Pattern

For applications that make many API calls, cache the token and re-authenticate only when it expires.

import os
import time
import requests

class AlphaSenseAuth:
"""Manages AlphaSense API authentication with automatic token refresh."""

AUTH_URL = "https://api.alpha-sense.com/auth"

def __init__(self):
self._token = None
self._expires_at = 0

def get_token(self) -> str:
"""Return a valid access token, refreshing if necessary."""
if self._token and time.time() < self._expires_at:
return self._token

headers = {
"x-api-key": os.environ["ALPHASENSE_API_KEY"],
"Content-Type": "application/x-www-form-urlencoded",
}

payload = {
"grant_type": "password",
"username": os.environ["ALPHASENSE_EMAIL"],
"password": os.environ["ALPHASENSE_PASSWORD"],
"client_id": os.environ["ALPHASENSE_CLIENT_ID"],
"client_secret": os.environ["ALPHASENSE_CLIENT_SECRET"],
}

response = requests.post(self.AUTH_URL, headers=headers, data=payload)
response.raise_for_status()

data = response.json()
self._token = data["access_token"]
# Refresh 5 minutes before actual expiry for safety
self._expires_at = time.time() + data["expires_in"] - 300

return self._token

def get_headers(self) -> dict:
"""Return headers dict ready for authenticated API calls."""
return {
"Authorization": f"Bearer {self.get_token()}",
"x-api-key": os.environ["ALPHASENSE_API_KEY"],
}

Quick Validation

Use the following one-liners to verify that your credentials are configured correctly.

python3 -c "
import os, requests
r = requests.post('https://api.alpha-sense.com/auth',
headers={'x-api-key': os.environ['ALPHASENSE_API_KEY'], 'Content-Type': 'application/x-www-form-urlencoded'},
data={'grant_type':'password','username':os.environ['ALPHASENSE_EMAIL'],'password':os.environ['ALPHASENSE_PASSWORD'],
'client_id':os.environ['ALPHASENSE_CLIENT_ID'],'client_secret':os.environ['ALPHASENSE_CLIENT_SECRET']})
print('Success' if r.ok else f'Error {r.status_code}: {r.text}')
"

Error Handling

Common authentication errors and how to resolve them:

HTTP StatusCauseResolution
400Missing or malformed request parametersVerify all required fields are present and grant_type is "password".
401Invalid credentials or expired tokenCheck your username, password, client ID, and client secret.
403Valid credentials but insufficient permissionsConfirm your API key is active and your account has Agent API access.
429Too many authentication requestsImplement token caching to reduce auth calls. Back off and retry.
500Server-side errorRetry after a brief delay. Contact support if the issue persists.
Related APIs The AlphaSense Agent API uses the same authentication mechanism as all other

AlphaSense APIs. If you have already integrated with another AlphaSense API, you can reuse the same credentials and token.

  • API Quick Start -- Get started with the full AlphaSense API suite using the same auth flow.
  • Explorer -- Interactively test API endpoints with your credentials. :::