如何在R语言中获取Sabre API的Token(类比Python实现方式)
Sabre's OAuth2 implementation uses the Client Credentials Flow for server-to-server authentication, which is straightforward to implement in R with the httr package. The oauth2.0_token function is more designed for flows requiring user interaction (like Authorization Code Flow), so we'll craft a direct POST request instead. Here's a step-by-step solution:
Step 1: Load Required Packages
First, install and load the packages we need for HTTP requests and base64 encoding:
# Install if not already installed if (!require(httr)) install.packages("httr") if (!require(base64enc)) install.packages("base64enc") library(httr) library(base64enc)
Step 2: Define Your Sabre Credentials
Replace the placeholder values with your actual credentials from the Sabre Developer Portal:
# Your Sabre client ID (format: V1:userid:group:domain) client_id <- "V1:your_user_id:your_group:your_domain" # Your Sabre client secret client_secret <- "your_client_secret_here"
Step 3: Encode Credentials for Authorization Header
Sabre requires your client ID and secret combined into a single string (client_id:client_secret), then base64-encoded for the Authorization header:
# Combine credentials and encode to base64 credentials <- paste0(client_id, ":", client_secret) encoded_credentials <- base64encode(charToRaw(credentials))
Step 4: Send POST Request to Token Endpoint
Choose the correct endpoint (sandbox for testing, production for live use) and send the request with the required parameters:
# Use sandbox endpoint for testing; swap with production endpoint when ready token_endpoint <- "https://api.test.sabre.com/v2/auth/token" # Production endpoint: "https://api.sabre.com/v2/auth/token" # Send POST request response <- POST( url = token_endpoint, add_headers( "Authorization" = paste("Basic", encoded_credentials), "Content-Type" = "application/x-www-form-urlencoded" ), body = list( grant_type = "client_credentials" ), encode = "form" )
Step 5: Parse and Extract the Access Token
Check if the request succeeded, then parse the JSON response to get your token:
# Check for HTTP errors stop_for_status(response) # Parse JSON response token_data <- content(response, as = "parsed") # Extract the access token (valid for 3600 seconds by default) access_token <- token_data$access_token # Print the token (optional) cat("Your Sabre API Access Token:\n", access_token, "\n")
Common Pitfalls to Avoid
- Incorrect Base64 Encoding: Ensure you don't add extra spaces or newlines when combining the client ID and secret.
- Wrong Endpoint: Double-check you're using the sandbox URL for testing (production requires additional approval).
- Invalid Credentials: If you get a 401 error, verify your client ID and secret are copied correctly from the Sabre portal.
- Missing Headers: The
Content-Typeheader must be set toapplication/x-www-form-urlencodedfor the request to be accepted.
Content of this question originates from Stack Exchange, asked by InDubio

