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.
| Parameter | Type | Location | Required | Description |
|---|---|---|---|---|
x-api-key | string | Header | Yes | Your AlphaSense API key. Identifies your registered application. |
grant_type | string | Body | Yes | Must always be "password". |
username | string | Body | Yes | The email address associated with your AlphaSense account. |
password | string | Body | Yes | The password for your AlphaSense account. |
client_id | string | Body | Yes | The OAuth2 client ID issued to your application. |
client_secret | string | Body | Yes | The OAuth2 client secret issued to your application. |
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
}
| Field | Type | Description |
|---|---|---|
access_token | string | The Bearer token to include in the Authorization header of all subsequent API requests. |
token_type | string | Always "Bearer". |
expires_in | integer | Token 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
- Python
- JavaScript
- cURL
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}"}
async function getAccessToken() {
const url = 'https://api.alpha-sense.com/auth'
const params = new URLSearchParams({
grant_type: 'password',
username: process.env.ALPHASENSE_EMAIL,
password: process.env.ALPHASENSE_PASSWORD,
client_id: process.env.ALPHASENSE_CLIENT_ID,
client_secret: process.env.ALPHASENSE_CLIENT_SECRET,
})
const response = await fetch(url, {
method: 'POST',
headers: {
'x-api-key': process.env.ALPHASENSE_API_KEY,
'Content-Type': 'application/x-www-form-urlencoded',
},
body: params.toString(),
})
if (!response.ok) {
const errorBody = await response.text()
throw new Error(`Authentication failed (${response.status}): ${errorBody}`)
}
const tokenData = await response.json()
return tokenData.access_token
}
// Usage
getAccessToken()
.then(token => {
console.log('Token acquired (expires in 24 hours)')
// Use the token in subsequent requests:
// const headers = { Authorization: `Bearer ${token}` };
})
.catch(err => console.error(err))
curl -X POST "https://api.alpha-sense.com/auth" \
-H "x-api-key: ${ALPHASENSE_API_KEY}" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=password" \
-d "username=${ALPHASENSE_EMAIL}" \
-d "password=${ALPHASENSE_PASSWORD}" \
-d "client_id=${ALPHASENSE_CLIENT_ID}" \
-d "client_secret=${ALPHASENSE_CLIENT_SECRET}"
Token Caching Pattern
For applications that make many API calls, cache the token and re-authenticate only when it expires.
- Python
- JavaScript
- cURL
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"],
}
class AlphaSenseAuth {
static AUTH_URL = 'https://api.alpha-sense.com/auth'
constructor() {
this.token = null
this.expiresAt = 0
}
async getToken() {
if (this.token && Date.now() < this.expiresAt) {
return this.token
}
const params = new URLSearchParams({
grant_type: 'password',
username: process.env.ALPHASENSE_EMAIL,
password: process.env.ALPHASENSE_PASSWORD,
client_id: process.env.ALPHASENSE_CLIENT_ID,
client_secret: process.env.ALPHASENSE_CLIENT_SECRET,
})
const response = await fetch(AlphaSenseAuth.AUTH_URL, {
method: 'POST',
headers: {
'x-api-key': process.env.ALPHASENSE_API_KEY,
'Content-Type': 'application/x-www-form-urlencoded',
},
body: params.toString(),
})
if (!response.ok) {
const errorBody = await response.text()
throw new Error(`Authentication failed (${response.status}): ${errorBody}`)
}
const data = await response.json()
this.token = data.access_token
// Refresh 5 minutes before actual expiry for safety
this.expiresAt = Date.now() + (data.expires_in - 300) * 1000
return this.token
}
async getHeaders() {
return {
Authorization: `Bearer ${await this.getToken()}`,
'x-api-key': process.env.ALPHASENSE_API_KEY,
}
}
}
#!/usr/bin/env bash
# Store the token in a variable for reuse across multiple requests
TOKEN=$(curl -s -X POST "https://api.alpha-sense.com/auth" \
-H "x-api-key: ${ALPHASENSE_API_KEY}" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=password" \
-d "username=${ALPHASENSE_EMAIL}" \
-d "password=${ALPHASENSE_PASSWORD}" \
-d "client_id=${ALPHASENSE_CLIENT_ID}" \
-d "client_secret=${ALPHASENSE_CLIENT_SECRET}" \
| python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])")
echo "Token acquired. Use it in subsequent requests:"
echo " curl -H \"Authorization: Bearer \$TOKEN\" ..."
Quick Validation
Use the following one-liners to verify that your credentials are configured correctly.
- Python
- JavaScript
- cURL
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}')
"
node -e "
(async()=>{const r=await fetch('https://api.alpha-sense.com/auth',{method:'POST',
headers:{'x-api-key':process.env.ALPHASENSE_API_KEY,'Content-Type':'application/x-www-form-urlencoded'},
body:new URLSearchParams({grant_type:'password',username:process.env.ALPHASENSE_EMAIL,
password:process.env.ALPHASENSE_PASSWORD,client_id:process.env.ALPHASENSE_CLIENT_ID,
client_secret:process.env.ALPHASENSE_CLIENT_SECRET}).toString()});
console.log(r.ok?'Success':'Error '+r.status+': '+await r.text())})()
"
curl -s -o /dev/null -w "%{http_code}" -X POST "https://api.alpha-sense.com/auth" \
-H "x-api-key: ${ALPHASENSE_API_KEY}" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=password&username=${ALPHASENSE_EMAIL}&password=${ALPHASENSE_PASSWORD}&client_id=${ALPHASENSE_CLIENT_ID}&client_secret=${ALPHASENSE_CLIENT_SECRET}" \
| xargs -I {} sh -c 'if [ "{}" = "200" ]; then echo "Success"; else echo "Error: HTTP {}"; fi'
Error Handling
Common authentication errors and how to resolve them:
| HTTP Status | Cause | Resolution |
|---|---|---|
400 | Missing or malformed request parameters | Verify all required fields are present and grant_type is "password". |
401 | Invalid credentials or expired token | Check your username, password, client ID, and client secret. |
403 | Valid credentials but insufficient permissions | Confirm your API key is active and your account has Agent API access. |
429 | Too many authentication requests | Implement token caching to reduce auth calls. Back off and retry. |
500 | Server-side error | Retry after a brief delay. Contact support if the issue persists. |
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. :::