Access Token Request for Userโ
The Access Token Request API is one of the vital component of the token generation workflow, designed to streamline the process of granting access to resources. It facilitates secure communication by triggering a user-driven approval process.
The following illustration depicts the flow and the actions performed by both the Initiator and the Account Holder.
Here's how the process works in detail:
Step 1: Initiating the Request
When the API is invoked, a request for an access token is generated. This triggers a notification to the user, informing them of the pending action required to either approve or reject the request.
Step 2: User Notification
The user is notified through multiple channels to ensure they are aware of the request. Notifications are sent via:
- In-App (Upstox Mobile/Web): A prompt appears within the Upstox mobile or web platform.
- WhatsApp: An additional notification is sent to the user's WhatsApp account for convenience.
These notifications provide the necessary details about the request, including the reason and origin, enabling the user to make an informed decision.
Step 3: User Action
The user can either approve or reject the request based on their discretion:
- Approval: If the user approves the request, the access token is securely transmitted to the designated Notifier Webhook Endpoint, which was configured during the app setup process. This ensures that the token reaches the appropriate endpoint for further use.
- Rejection: If the user rejects the request, the token generation process is terminated, and the request is discarded. No token is created or sent.
Note: It is crucial to distinguish this API from the standard token generation API, which is used for generating tokens independently by the Account Holder without external initiation.
Requestโ
curl -X 'POST' 'https://api.upstox.com/v3/login/auth/token/request/678d46e1-91ac-4b8d-925d-89c8e3015c2b' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"client_secret": "{your_client_secret}"
}'
For additional samples in various languages, please refer to the Sample code section on this page.
Path Parametersโ
Name | Required | Type | Description |
---|---|---|---|
client_id | true | string | The API key obtained during the app generation process. |
Request Bodyโ
Name | Required | Type | Description |
---|---|---|---|
client_secret | true | string | The API secret obtained during the app generation process. This private key remains confidential, known only to the application and the authorization server. |
- 200
- 4XX
Response Bodyโ
{
"status": "success",
"data": {
"authorization_expiry": "1732226400000",
"notifier_url": "https://initiator-webhook-endpoint"
}
}
Name | Type | Description |
---|---|---|
status | string | A string indicating the outcome of the request. Typically success for successful operations. |
data | object | Response data for token request |
data.authorization_expiry | string | An expiration time for the access token generation process, starting from the moment a initiator requests the token until the 3:30 AM the following day. |
data.notifier_url | string | The Notifier webhook endpoint where the access token is to be sent. The Notifier webhook endpoint must be configured during the app generation process. |
{
"status": "error",
"errors": [
{
"errorCode": "UDAPI1123",
"message": "Invalid notifier url",
"propertyPath": null,
"invalidValue": null,
"error_code": "UDAPI1123",
"property_path": null,
"invalid_value": null
}
]
}
For more details, refer to the Error Response documentation.
Error codesโ
Error code | Description |
---|---|
UDAPI100069 | Check your 'client_id' and 'client_secret'; one or both are incorrect. - Thrown when one of the credentials you've passed to this API is invalid. |
UDAPI1123 | Invalid notifier url - Thrown when the notifier_url not configured during app generation process. |
UDAPI1124 | Invalid user type - Thrown when the access token request is not for an individual user. |
Notifier Webhookโ
Once the user approves the initiator's request to generate an access token, the Upstox API will send the following payload to the specified notifier webhook URL:
Response structure:โ
{
"client_id": "615b1297-d443-3b39-ba19-1927fbcdddc7",
"user_id": "******",
"access_token": "*********",
"token_type": "Bearer",
"expires_at": "1731448800000",
"issued_at": "1731412800000",
"message_type": "access_token"
}
Name | Type | Description |
---|---|---|
client_id | string | The API key associated with the app during its generation process, for which the access token has been successfully generated. |
user_id | string | Uniquely identifies the user (commonly referred as UCC) |
access_token | string | The generated authentication token to be used for all subsequent API requests. |
token_type | string | The type of token issued, indicating the authentication scheme to be used, such as Bearer . |
expires_at | string | The timestamp indicating when the access token will expire. After this time, the token will no longer be valid for making API requests and a new token may need to be generated. |
issued_at | string | The timestamp indicating when the access token was issued. It represents the exact time the token was generated. |
message_type | string | The type of webhook response sent to the notifier url. such as access_token |
Authorization Expiryโ
The access token request to obtain the access_token
has a defined validity period that expires at 3:30 AM the following day, unless the user approves it sooner.
For example:
- If the initiator requests the token at 8:00 PM on Tuesday, the request will expire at 3:30 AM on Wednesday, at which point it will expire.
- Similarly, if the request is initiated at 2:30 AM on Wednesday, it will still expire at 3:30 AM on the same Wednesday.
Users are encouraged to approve the access token request promptly, keeping the expiration schedule in mind to ensure smooth access and usage.
Sample Codeโ
Access token requestโ
- Python
- Node.js
- Java
- PHP
- Python SDK
- Node.js SDK
- Java SDK
import requests
url = 'https://api.upstox.com/v3/login/auth/token/request/678d46e1-91ac-4b8d-925d-89c8e3015c2b'
headers = {
'accept': 'application/json',
'Content-Type': 'application/json',
}
data = {
'client_secret': '{your_client_secret}'
}
response = requests.post(url, headers=headers, data=data)
print(response.status_code)
print(response.json())
const axios = require('axios');
const url = 'https://api.upstox.com/v3/login/auth/token/request/678d46e1-91ac-4b8d-925d-89c8e3015c2b';
const headers = {
'accept': 'application/json',
'Content-Type': 'application/json',
};
const data = {
'client_secret': '{your_client_secret}'
};
axios.post(url, new URLSearchParams(data), { headers })
.then(response => {
console.log(response.status);
console.log(response.data);
})
.catch(error => {
console.error(error.response.status);
console.error(error.response.data);
});
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws Exception {
String apiUrl = "https://api.upstox.com/v3/login/auth/token/request/678d46e1-91ac-4b8d-925d-89c8e3015c2b";
HttpURLConnection con = (HttpURLConnection) new java.net.URL(apiUrl).openConnection();
// Set the request method
con.setRequestMethod("POST");
// Set the request headers
con.setRequestProperty("accept", "application/json");
con.setRequestProperty("Content-Type", "application/json");
// Enable input/output streams
con.setDoOutput(true);
// Set the request data
String data = "{"
+ "\"client_secret\": \"{your_client_secret}\""
+ "}";
// Write the request data to the output stream
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.write(data.getBytes(StandardCharsets.UTF_8));
wr.flush();
}
// Get the response code
int responseCode = con.getResponseCode();
System.out.println("Response Code: " + responseCode);
// Read the response
try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
// Print the response
System.out.println(response.toString());
}
}
}
<?php
$url = 'https://api.upstox.com/v3/login/auth/token/request/678d46e1-91ac-4b8d-925d-89c8e3015c2b';
$headers = [
'accept: application/json',
'Content-Type: application/json',
];
$data = [
'client_secret' => '{your_client_secret}'
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo "Response Code: $httpCode\n";
echo "Response Data: $response\n";
?>
import upstox_client
from upstox_client.rest import ApiException
configuration = upstox_client.Configuration()
api_instance = upstox_client.LoginApi(upstox_client.ApiClient(configuration))
body = upstox_client.IndieUserTokenRequest(client_secret="****")
try:
api_response = api_instance.init_token_request_for_indie_user(body,client_id="*****")
print(api_response)
except ApiException as e:
print("Exception when calling indie token request: %s\n" % e)
let UpstoxClient = require('upstox-js-sdk');
let apiInstance = new UpstoxClient.LoginApi();
let body = new UpstoxClient.IndieUserTokenRequest();
body.clientSecret = "your_client_secret"; // Replace with your actual client secret
apiInstance.initTokenRequestForIndieUser(body,"your_client_id", (error, data, response) => {
if (error) {
console.error(error.response.text);
} else {
console.log('API called successfully. Returned data: ' + JSON.stringify(data));
}
});
import com.upstox.ApiException;
import com.upstox.api.IndieUserInitTokenResponse;
import com.upstox.api.IndieUserTokenRequest;
import io.swagger.client.api.LoginApi;
public class Main {
public static void main(String[] args) {
LoginApi loginApi = new LoginApi();
IndieUserTokenRequest indieUserTokenRequest = new IndieUserTokenRequest();
indieUserTokenRequest.setClientSecret("your_client_secret");
try {
IndieUserInitTokenResponse indieUserInitTokenResponse = loginApi.initTokenRequestForIndieUser(indieUserTokenRequest, "your_client_id");
System.out.println(indieUserInitTokenResponse);
} catch (ApiException e) {
System.out.println(e.getResponseBody());
throw new RuntimeException(e);
}
}
}