Good to know: This is the best way to get started using the Valor API from authorization to making your first request for your desired application.
API Authentication
Your API requests are authenticated using a JWT Bearer token. Any request that doesn't include this token will return an error.
You can obtain the token by providing your Valor username and password along with a provided client_id and user_pool_id:
Note: Contact Valor Biomechanics to obtain the client_id and user_pool_id
# Make the AWS Cognito authentication request using curlresponse=$(awscognito-idpinitiate-auth \--auth-flowUSER_PASSWORD_AUTH \--auth-parametersUSERNAME=your_username,PASSWORD=your_password \--client-idyour_client_id)# Extract the JWT token from the JSON responsejwt_token=$(echo"$response"|jq-r'.AuthenticationResult.IdToken')# Print the JWT tokenecho"JWT Token: $jwt_token"
import boto3# Initialize a Cognito Identity Provider clientcognito = boto3.client('cognito-idp', region_name='us-east-1')# Define user authentication detailsusername ='your_username'password ='your_password'client_id ='your_client_id'user_pool_id ='your_user_pool_id'# Authenticate the user and obtain a JWT tokenresponse = cognito.initiate_auth( AuthFlow='USER_PASSWORD_AUTH', AuthParameters={'USERNAME': username,'PASSWORD': password, }, ClientId=client_id, AuthFlowMetadata={'UserPoolId': user_pool_id })# Extract the JWT token from the responsejwt_token = response['AuthenticationResult']['AccessToken']print(jwt_token)
constAmazonCognitoIdentity=require('amazon-cognito-identity-js');// Create a user pool objectconstpoolData= { UserPoolId:'your_user_pool_id', ClientId:'your_client_id'};constuserPool=newAmazonCognitoIdentity.CognitoUserPool(poolData);// Define user authentication detailsconstauthenticationData= { Username:'your_username', Password:'your_password'};// Create a Cognito user objectconstauthenticationDetails=newAmazonCognitoIdentity.AuthenticationDetails(authenticationData);constuserData= { Username:'your_username', Pool: userPool};constcognitoUser=newAmazonCognitoIdentity.CognitoUser(userData);// Authenticate the user and obtain a JWT tokencognitoUser.authenticateUser(authenticationDetails, {onSuccess: (session) => {constjwtToken=session.getAccessToken().getJwtToken();console.log(jwtToken); },onFailure: (error) => {console.error(error); }});
import React, { useState } from'react';constYourComponent= () => {const [username,setUsername] =useState('');const [password,setPassword] =useState('');const [token,setToken] =useState('');consthandleLogin=async () => {try {constresponse=awaitfetch('https://your-cognito-endpoint.auth.us-east-1.amazoncognito.com/oauth2/token', { method:'POST', headers: {'Content-Type':'application/x-www-form-urlencoded', }, body:newURLSearchParams({ grant_type:'password', client_id:'your-client-id', username: username, password: password, }).toString(), } );if (!response.ok) {thrownewError('Authentication failed'); }constdata=awaitresponse.json();constaccessToken=data.access_token;// Store the access token in state or a context for later usesetToken(accessToken); } catch (error) {console.error('Authentication error:', error); } };return ( <div> <h2>Login</h2> <inputtype="text"placeholder="Username"value={username}onChange={(e) =>setUsername(e.target.value)} /> <inputtype="password"placeholder="Password"value={password}onChange={(e) =>setPassword(e.target.value)} /> <buttononClick={handleLogin}>Login</button> {token && ( <div> <h3>JWT Token</h3> <pre>{token}</pre> </div> )} </div> );};exportdefault YourComponent;
importAWSCognitoIdentityProvider// Define user authentication detailslet username ="your_username"let password ="your_password"let userPoolId ="your_user_pool_id"let clientId ="your_client_id"// Create a Cognito user pool objectlet serviceConfiguration =AWSServiceConfiguration( region: .USEast1, credentialsProvider:nil)let poolConfiguration =AWSCognitoIdentityUserPoolConfiguration( clientId: clientId, clientSecret:nil, poolId: userPoolId)AWSCognitoIdentityUserPool.register( with: serviceConfiguration, userPoolConfiguration: poolConfiguration, forKey:"UserPoolKey")let userPool =AWSCognitoIdentityUserPool(forKey:"UserPoolKey")// Authenticate the user and obtain a JWT tokenlet user = userPool.getUser(username)let authDetails =AWSCognitoIdentityPasswordAuthenticationDetails( username: username, password: password, validationData:nil)user?.getSession( username, password: password, validationData:nil).continueWith { (task) iniflet error = task.error {print("Authentication error: \(error.localizedDescription)") } elseiflet session = task.result {print("JWT Token: \(session.accessToken?.tokenString ??"")") }returnnil}
API Protocols and Headers
The Valor API uses only GET requests to retrieve data and HTTP response codes to communicate request status and errors. All API requests must be made over HTTPS. Calls made over plain HTTP will fail. API requests without authentication will also fail.
The Valor API uses a combination of JSON and URL-encoded query parameters to send data to and from the API. When sending JSON data to the API in the request body, the content type of your request must be set to application/json. When receiving data from the API, the content type of your response will always be application/json. All response bodies, including errors, will be sent in JSON format. In the event of an error, the response body will contain details about the error.
API Host
All requests to the Valor API should be made to the following host:
The Valor API uses traditional or conventional HTTP response codes to indicate the success or failure of an API request.
In general, codes in the 2xx range indicate success, codes in the 4xx range indicate an error that failed given the information provided (e.g., a required parameter was omitted, a provided parameter was invalid, etc.), and codes in the 5xx range indicate an error with the Valor API (these are rare). When possible, the API will also return a JSON response body with additional information about the error.
Code
Name
Description
400
Bad Request Body or Parameters
The gateway response when the request body OR parameter cannot be validated according to an enabled request validator. Accompanying error message should explain in further detail.
401
Unauthorized
The gateway response when the API authorizer failed to authenticate the caller.
The gateway response for authentication failure. Accompanying error message should explain in further detail.
404
Resource not found
The gateway response when API cannot find the specified resource after an API request passes authentication and authorization, except for API key authentication and authorization.
413
Request too large
The gateway response for the request too large error.
415
Unsupported media type
The gateway response when a payload is of an unsupported media type, if strict passthrough behavior is enabled.
429
Quota exceeded or Throttled
The gateway response for the usage plan quota exceeded error.
500/504
Internal Server Error
Something is broken. Please contact us at info@bravevirtual.com and let us know what you were trying to do when this error occurred. We will try to get it fixed as soon as possible.
Make your first request
To make your first request, send an authenticated request to the athletes endpoint. This will allow for you to return all athlete objects and their information if needed.
{"message":"String type - this will contain more details about the problem encountered"}
{"message":"String type - this will contain more details about the problem encountered"}
The endpoint URL to the API is provided next to the API method (see above)
Take a look at how you might call this method using using the following languages:
# Replace 'your_jwt_token' with the actual JWT token obtained from Cognito# Replace 'your_limit' and 'your_page' with the desired values for limit and pagejwt_token="your_jwt_token"# Make a GET request to the API server with JWT token and query string parameterscurl-XGET"your_api_invoke_url_by_path?athleteID=${athleteID}" \-H"Authorization: Bearer ${jwt_token}"
import requests# Replace 'your_jwt_token' with the actual JWT token obtained from Cognitojwt_token ='your_jwt_token'url ="your_api_invoke_url_by_path"# Replace these values with the desired limit and page valuesparams ={"athleteID":"your_unique_athlete_ID"}headers ={"Authorization":f"Bearer {jwt_token}"}response = requests.get(url, headers=headers, params=params)if response.status_code ==200: data = response.json()# Process the JSON data hereelse:print("Failed to fetch data from the API")
constfetch=require('node-fetch');// Replace 'your_jwt_token' with the actual JWT token obtained from CognitoconstjwtToken='your_jwt_token';consturl="your_api_invoke_url_by_path";// Replace these values with the desired limit and page valuesconstqueryParams=newURLSearchParams({"athleteID":"your_unique_athlete_ID"});constheaders= {"Authorization":`Bearer ${jwtToken}`};fetch(`${url}?${queryParams}`, { headers }).then(response =>response.json()).then(data => {// Process the JSON data here }).catch(error => {console.error("Failed to fetch data from the API:", error); });
import React, { useEffect, useState } from'react';constYourComponent= () => {const [data,setData] =useState([]);// Replace 'your_jwt_token' with the actual JWT token obtained from CognitoconstjwtToken='your_jwt_token';// Replace these values with the desired limit, page, or athleteID valuesconstathleteID="your_unique_athlete_ID";useEffect(() => {constfetchData=async () => {try {constqueryParams=newURLSearchParams({"athleteID": athleteID });constresponse=awaitfetch(`your_api_invoke_url_by_path?${queryParams}`, { headers: {"Authorization":`Bearer ${jwtToken}` } });if (response.ok) {constjsonData=awaitresponse.json();setData(jsonData); } else {console.error("Failed to fetch data from the API"); } } catch (error) {console.error("Error fetching data:", error); } };fetchData(); }, []);return ( <div> {/* Render the fetched data here */} </div> );};exportdefault YourComponent;
importSwiftUIstructAthleteData:Codable {// Define your data model here to match the API response structure}structContentView:View {@Stateprivatevar data: AthleteData?// Replace 'your_jwt_token' with the actual JWT token obtained from Cognitolet jwtToken ="your_jwt_token"// Replace with the desired athleteIDlet athleteID ="your_unique_athlete_id"var body: some View {VStack {// Render the fetched data here } .onAppear() {fetchData() } }funcfetchData() {var urlComponents =URLComponents(string:"your_api_invoke_url_by_path")! urlComponents.queryItems = [URLQueryItem(name:"athleteID", value:String(athleteID)) ]let url = urlComponents.url!var request =URLRequest(url: url) request.setValue("Bearer \(jwtToken)", forHTTPHeaderField:"Authorization") URLSession.shared.dataTask(with: request) { (data, _, _) iniflet data = data {do {let decoder =JSONDecoder()let decodedData =try decoder.decode(AthleteData.self, from: data) self.data = decodedData } catch {print("Error decoding data:", error) } } }.resume() }}@mainstructYourApp:App {var body: some Scene {WindowGroup {ContentView() } }}