Get Token
API to acquire an access token via an authorization_code exchange and concurrently includes the user's profile in the response.
The access_token
obtained through this API has a specific validity period that lasts until 3:30 AM
the following day, regardless of the time it was generated. For instance, if you generate a token at 8 PM on Tuesday, it will expire at 3:30 AM on Wednesday. This also means that a token created at 2:30 AM on Wednesday will still expire at 3:30 AM on the same Wednesday. Therefore, users are advised to plan their activities accordingly, ensuring they accommodate the token's expiration schedule in their usage.
The code
sent as part of this request is valid for a single use, regardless of whether the access token generation succeeds or encounters an issue.
Request
curl -X 'POST' 'https://api.upstox.com/v2/login/authorization/token' \
-H 'accept: application/json' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'code={your_code}&client_id={your_client_id}&client_secret={your_client_secret}&redirect_uri={your_redirect_url}&grant_type=authorization_code'
For additional samples in various languages, please refer to the Sample code section on this page.
Request Body
Name | Required | Type | Description |
---|---|---|---|
code | true | string | The code is a unique parameter included in the URL upon a successful Authorize API authentication. |
client_id | true | string | The API key obtained during the app generation process. |
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. |
redirect_uri | true | string | The URL provided during app generation. |
grant_type | true | string | This value must always be authorization_code . |
- 200
- 4XX
Response Body
{
"email": "******",
"exchanges": ["NSE", "NFO", "BSE", "CDS", "BFO", "BCD"],
"products": ["D", "CO", "I"],
"broker": "UPSTOX",
"user_id": "******",
"user_name": "******",
"order_types": ["MARKET", "LIMIT", "SL", "SL-M"],
"user_type": "individual",
"poa": false,
"is_active": true,
"access_token": "******************"
"extended_token": "******************"
}
Name | Type | Description |
---|---|---|
string | E-mail address of the user | |
exchanges | string[] | List of exchanges enabled for the user. Valid exchanges can be found in the Exchange Appendix |
products | string[] | Lists the types of products enabled for the user. Possible values: I , D , CO , MTF |
broker | string | The broker ID |
user_id | string | Uniquely identifies the user (commonly referred as UCC) |
user_name | string | Name of the user |
order_types | string[] | Order types enabled for the user. Possible values: MARKET , LIMIT , SL , SL-M |
user_type | string | Identifies the user's registered role with the broker. This will be individual for all retail users |
poa | boolean | Indicates whether the user has authorized power of attorney for transactions. |
is_active | boolean | Indicates if the account status is active. |
access_token | string | The authentication token to be used with every subsequent API request. |
extended_token | string | This token is designed for prolonged usage, primarily for read-only access to various API endpoints. For more detailed information on the extended token, including its benefits and how to opt for it, please refer to the Extended Token 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. |
UDAPI100070 | The 'redirect_uri' provided is invalid. Please enter the valid URI and try again. - Thrown when the redirect_uri passed to this API is invalid. |
UDAPI100057 | Invalid Auth code - Thrown when the code value passed to the API is invalid. |
Sample Code
Get access token using auth code
- Python
- Node.js
- Java
- PHP
- Python SDK
- Node.js SDK
- Java SDK
import requests
url = 'https://api.upstox.com/v2/login/authorization/token'
headers = {
'accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
}
data = {
'code': '{your_code}',
'client_id': '{your_client_id}',
'client_secret': '{your_client_secret}',
'redirect_uri': '{your_redirect_url}',
'grant_type': 'authorization_code',
}
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/v2/login/authorization/token';
const headers = {
'accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
};
const data = {
'code': '{your_code}',
'client_id': '{your_client_id}',
'client_secret': '{your_client_secret}',
'redirect_uri': '{your_redirect_url}',
'grant_type': 'authorization_code',
};
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/v2/login/authorization/token";
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/x-www-form-urlencoded");
// Enable input/output streams
con.setDoOutput(true);
// Set the request data
String data = "code={your_code}" +
"&client_id={your_client_id}" +
"&client_secret={your_client_secret}" +
"&redirect_uri={your_redirect_url}" +
"&grant_type=authorization_code";
// 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/v2/login/authorization/token';
$headers = [
'accept: application/json',
'Content-Type: application/x-www-form-urlencoded',
];
$data = [
'code' => '{your_code}',
'client_id' => '{your_client_id}',
'client_secret' => '{your_client_secret}',
'redirect_uri' => '{your_redirect_uri}',
'grant_type' => 'authorization_code',
];
$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
api_instance = upstox_client.LoginApi()
api_version = '2.0'
code = '{your_auth_code}'
client_id = '{your_client_id}'
client_secret = '{your_client_secret}'
redirect_uri = '{your_redirect_url}'
grant_type = 'grant_type_example'
try:
# Get token API
api_response = api_instance.token(api_version, code=code, client_id=client_id, client_secret=client_secret,
redirect_uri=redirect_uri, grant_type=grant_type)
print(api_response)
except ApiException as e:
print("Exception when calling LoginApi->token: %s\n" % e)
let UpstoxClient = require('upstox-js-sdk');
let apiInstance = new UpstoxClient.LoginApi();
let apiVersion = "2.0";
let opts = {
'code': "{your_auth_code}",
'clientId': "{your_client_secret}",
'clientSecret': "{your_client_secret}",
'redirectUri': "{your_redirect_url}",
'grantType': "authorization_code"
};
apiInstance.token(apiVersion, opts, (error, data, response) => {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + JSON.stringify(data));
}
});
import com.upstox.ApiException;
import com.upstox.api.TokenResponse;
import io.swagger.client.api.LoginApi;
public class Main {
public static void main(String[] args) {
LoginApi apiInstance = new LoginApi();
String apiVersion = "2.0";
String code = "{your_code}";
String clientId = "{your_clientId}";
String clientSecret = "{your_clientSecret}";
String redirectUri = "{your_redirect_url}";
String grantType = "authorization_code";
try {
TokenResponse result = apiInstance.token(apiVersion, code, clientId, clientSecret, redirectUri, grantType);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling LoginApi#token");
e.printStackTrace();
}
}
}