# Required package requests: `pip install requests`
import json
import base64
import requests
# Using of Client Credentials authorization flow.
# Insert your client credentials received in welcome email.
client_id = "your_client_id"
client_secret = "your_client_secret"
identity_url = "https://id.livevol.com/connect/token"
api_url = "https://api.livevol.com/v1/delayed/allaccess/market/underlying-quotes?symbols=AAPL&date=2019-01-18"
authorization_token = base64.b64encode((client_id + ':' + client_secret).encode())
headers = {"Authorization": "Basic " + authorization_token.decode('ascii')}
payload = {"grant_type": "client_credentials"}
# Requesting access token
token_data = requests.post(identity_url, data=payload, headers=headers)
if token_data.status_code == 200:
access_token = token_data.json()['access_token']
if len(access_token) > 0:
print("Authenticated successfully")
# Requesting data from API
result = requests.get(api_url, headers={"Authorization": "Bearer " + access_token})
print(result.json())
else:
print("Authentication failed")
// Required packages: Newtonsoft.Json
// Using of Client Credentials authorization flow.
// Insert your client credentials received in welcome email.
var clientId = "your_client_id";
var clientSecret = "your_client_secret";
var identityUrl = "https://id.livevol.com/connect/token";
var apiUrl = "https://api.livevol.com/v1/delayed/allaccess/market/underlying-quotes?symbols=AAPL&date=2019-01-18";
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}")));
var response = httpClient.PostAsync(identityUrl,
new FormUrlEncodedContent(
new Dictionary<string, string>()
{
{ "grant_type", "client_credentials"}
})).GetAwaiter().GetResult();
response.EnsureSuccessStatusCode();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer", JObject.Parse(response.Content.ReadAsStringAsync().GetAwaiter().GetResult()).Value<string>("access_token"));
var data = httpClient.GetStringAsync(apiUrl).GetAwaiter().GetResult();
Console.WriteLine(data);
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
// Using of Client Credentials authorization flow.
// Insert your client credentials received in welcome email.
var clientId = "your_client_id";
var clientSecret = "your_client_secret";
var identityUrl = "https://id.livevol.com/connect/token";
var apiUrl = "https://api.livevol.com/v1/delayed/allaccess/market/underlying-quotes?symbols=AAPL&date=2019-01-18"
// Requesting access token
function getAccesToken(url, client_id, client_secret) {
return $.ajax({
method: "POST",
url: url,
headers: {
Authorization: "Basic " + btoa(client_id + ':' + client_secret)
},
data: {
grant_type: "client_credentials"
}
});
}
// Requesting data from API
function callApi(url, access_token) {
return $.ajax({
method: "GET",
url: url,
headers: {
Authorization: "Bearer " + access_token
}
});
}
function show(mes) { alert(JSON.stringify(mes, null, ' ')) }
function showError(error) { show(error) }
getAccesToken(identityUrl, clientId, clientSecret)
.done(function (result) {
callApi(apiUrl, result.access_token)
.done(function (result) {
show(result);
})
.fail(showError)
})
.fail(showError)
</script>
// <dependencies>
// <dependency>
// <groupId>org.apache.httpcomponents</groupId>
// <artifactId>httpclient</artifactId>
// <version>4.5.12</version>
// </dependency>
// <dependency>
// <artifactId>json-simple</artifactId>
// <groupId>com.googlecode.json-simple</groupId>
// <version>1.1.1</version>
// </dependency>
// </dependencies>
// Using of Client Credentials authorization flow.
// Insert your client credentials received in welcome email.
String clientId = "your_client_id";
String clientSecret = "your_client_secret";
String identityUrl = "https://id.livevol.com/connect/token";
String apiUrl = "https://api.livevol.com/v1/delayed/allaccess/market/underlying-quotes?symbols=AAPL&date=2019-01-18";
// Requesting access token
String authorizationToken = Base64.encodeBase64String((clientId + ":" + clientSecret).getBytes(StandardCharsets.UTF_8));
CloseableHttpClient httpclient = HttpClients.custom().build();
HttpPost httpPost = new HttpPost(identityUrl);
httpPost.addHeader("Authorization", "Basic " + authorizationToken);
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("grant_type", "client_credentials"));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters, StandardCharsets.UTF_8));
CloseableHttpResponse response = httpclient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
JSONObject object = (JSONObject) new JSONParser().parse(EntityUtils.toString(response.getEntity()));
String accessToken = (String) object.get("access_token");
System.out.println("Authenticated successfully");
// Requesting data from API
httpclient = HttpClients.custom().build();
HttpGet httpGet = new HttpGet(apiUrl);
httpGet.addHeader("Authorization", "Bearer " + accessToken);
response = httpclient.execute(httpGet);
System.out.println(EntityUtils.toString(response.getEntity()));
} else {
System.out.println("Authentication failed");
}
require(RCurl)
require(httr)
# Enter your client credentials
client_id <- 'enter your client id'
client_secret <- 'enter your client secret'
encoded_credentials <- base64Encode(paste(client_id, ':', client_secret, sep=''))
# Request access token
get_token <- POST('https://id.livevol.com/connect/token', body='grant_type=client_credentials', add_headers(Authorization=paste('Basic ', encoded_credentials, sep='')))
content(get_token)
if (get_token$status_code == 200) {
print('Authentication successful')
parse_response <- content(get_token, as = 'parsed')
access_token <- parse_response['access_token']
response <- GET('https://api.livevol.com/v1/delayed/allaccess/market/underlying-quotes?date=2021-08-16&symbols=AAPL', add_headers(Authorization=paste('Bearer ', access_token, sep='')))
content(response)
} else {
print('Authentication failed')
}
Compressing responses with gzip
Responses are returned gzip-compressed whenever the request carries an
Accept-Encoding: gzip header. On large payloads the saving is substantial:
a full ^SPX option chain from
option-and-underlying-quotes transfers as roughly
1.8 MB instead of 16.5 MB — about a 9× reduction.
The decoded body is byte-for-byte identical either way.
Only gzip is supported. A request advertising
only br (Brotli) or only deflate receives
the full uncompressed response — silently, with no error. Include
gzip in the list; a combined value such as
br, gzip negotiates down correctly.
To confirm it worked, check that the response carries
Content-Encoding: gzip. Some clients hide that header: .NET
HttpClient and axios remove it after decoding, and a browser hides it
on cross-origin calls. In those cases check with curl (see the C# or JavaScript example).
Most HTTP clients request and decode gzip for you automatically. The notable
exceptions are C# and Java's built-in
java.net.http.HttpClient, which need to be configured
explicitly — select your language above.
# requests already sends `Accept-Encoding: gzip, deflate` and decodes the
# response for you, so no configuration is required.
result = requests.get(api_url, headers={"Authorization": "Bearer " + access_token})
print(result.headers.get("Content-Encoding")) # -> 'gzip'
# CAUTION: len(result.content) is the DECODED size, not the bytes received.
# Measuring it will make a compressed response look uncompressed.
print(len(result.content)) # ~16,970,000 (decoded)
# To see what actually crossed the network, read the raw stream:
raw = requests.get(api_url,
headers={"Authorization": "Bearer " + access_token},
stream=True)
print(len(raw.raw.read())) # ~1,860,000 (on the wire)
// HttpClient does NOT decompress by default: AutomaticDecompression is
// DecompressionMethods.None unless you set it. Without this, you receive
// the full uncompressed body.
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
var handler = new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip
};
using var client = new HttpClient(handler);
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);
// Accept-Encoding: gzip is now sent for you, and the body is decoded
// transparently before you read it.
var response = await client.GetAsync(apiUrl);
var json = await response.Content.ReadAsStringAsync();
// Note: once HttpClient has decoded the body it removes Content-Encoding
// (and Content-Length), so response.Content.Headers.ContentEncoding is empty
// even when the response WAS compressed. Do not remove AutomaticDecompression
// to "fix" that -- verify with curl (a GET, not -I) instead:
// curl -s -o /dev/null -D - -H 'Accept-Encoding: gzip' -H "Authorization: Bearer $TOKEN" "URL"
// (On Windows run curl.exe, not the PowerShell curl alias, and use -o NUL.)
// In a browser, Accept-Encoding is controlled by the browser and cannot be
// set from JavaScript -- it is a forbidden header name. fetch() therefore
// already receives gzip and decodes it; nothing to configure.
const response = await fetch(apiUrl, {
headers: { "Authorization": "Bearer " + accessToken }
});
const data = await response.json();
// In Node.js, the built-in fetch() (undici) also decodes gzip automatically.
// With axios, decompression is enabled by default (decompress: true).
// Note: axios removes Content-Encoding after decoding, and a browser hides it
// on cross-origin calls (it is not a CORS-safelisted header). Node's fetch()
// keeps it. To prove compression regardless of client, use curl (a GET --
// not -I, since a HEAD response has no body to compress):
// curl -s -o /dev/null -D - -H 'Accept-Encoding: gzip' -H "Authorization: Bearer $TOKEN" "URL"
// Apache HttpClient (used in the example above) requests and decodes gzip
// automatically -- no change needed there.
// java.net.http.HttpClient does NOT. You must ask for gzip and decode it:
import java.util.zip.GZIPInputStream;
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(apiUrl))
.header("Authorization", "Bearer " + accessToken)
.header("Accept-Encoding", "gzip")
.build();
HttpResponse<InputStream> response =
client.send(request, HttpResponse.BodyHandlers.ofInputStream());
boolean gzipped = "gzip".equalsIgnoreCase(
response.headers().firstValue("Content-Encoding").orElse(""));
try (InputStream body = gzipped
? new GZIPInputStream(response.body())
: response.body()) {
// read the JSON from `body`
}
# httr is built on libcurl, which advertises gzip and decodes the response
# automatically. No configuration is required.
response <- GET('https://api.livevol.com/v1/delayed/allaccess/market/underlying-quotes?date=2021-08-16&symbols=AAPL',
add_headers(Authorization=paste('Bearer ', access_token, sep='')))
content(response)
# Confirm the response was compressed in transit:
headers(response)$`content-encoding` # -> "gzip"