Use OAuth 2.0 to authorize your application when accessing the hotel APIs.
OAuth 2.0 setup
OAuth 2.0 requires that you identify yourself using a service account associated with your Google Account. The service account sends your private key in exchange for an OAuth 2.0 access token. You can then use this token in calls to the hotel APIs for read-only data, such as pricing, hotel, and diagnostic reporting data about your hotel price feed.
Access tokens are good for an hour (3,600 seconds).
If you previously implemented ClientLogin, the OAuth 2.0 approach is similar, with the following differences:
- Your application uses a Google service account to access the API.
- You pass an OAuth 2.0 access token in the
AuthorizationHTTP header when calling APIs.
To set up your account to use OAuth 2.0 with the Travel Partner API, perform these steps:
Each of these steps is described in the sections that follow.
Step 1: Create a new DevConsole Project
The Google Developers Console ('DevConsole') is Google's developer experience for managing and viewing traffic data, authentication, and billing information for the Google APIs that your projects use.
In the DevConsole, a project is a collection of settings, credentials, and metadata about the application or applications that you're working on which uses Google Developer APIs and Google Cloud resources.
The DevConsole is where you manage these aspects of your project, such as generating API credentials, activating APIs, and managing team and billing information associated with your project.
To create a new DevConsole project:
Sign in to your Gmail/Google Account.
Open the Google Developer Console. If this is your first project, the main view displays a simple CREATE PROJECT button:
Click the CREATE PROJECT button. DevConsole displays the New Project dialog box:
Enter a friendly name for your new project in the Project name input field. Below the field, the DevConsole generates a project ID for you, ensuring that the ID is unique across all projects. For example, if you enter "My New Project", DevConsole assigns an ID like
Click the Create button to create your new project.
Use the navigation menu to select APIs & Services > Dashboard.
The image below shows the navigation menu in the upper left of the DevConsole. This displays the Dashboard view for your project:
For more information, refer to Manage projects in the Developers Console.
When you create a new project, it has no APIs associated with it yet. In the next step, you will enable the Travel Partner API for your new Project.
Step 2: Enable the Travel Partner API for the new project
To use the hotel APIs, you must enable Travel Partner API in your new DevConsole project.
To enable the hotel APIs for your new project:
Go to the Dashboard view of your project as described above.
Click Enable APIs and Services. This displays the API Library welcome page.
In the search field, start typing Travel Partner API. The Google API Console displays a list of APIs that match what you type.
Click Travel Partner API in the table of matching APIs. DevConsole displays a description about the API.
Click the Enable API button to enable this API for your project.
For more information, refer to Activate and deactivate APIs.
The Hotel APIs are now enabled for your Google Account's new project.
The next step is to create a service account and generate keys for it.
Step 3: Create a service account and generate its credentials
Service accounts are used by server-to-server interactions such as those between a web application and your hotel data.
To create and configure a service account:
In the Google API Console main view, click Credentials in the left-hand navigation. DevConsole displays the Credentials view.
The Credentials view displays client IDs and credentials for your project. Your application will use the client ID when requesting an OAuth 2.0 access token. New projects will have no clients or credentials yet.
Click the Credentials in APIs and services link.
Click the Create credentials button, and select Service account key from the dropdown. The Create service account key view displays.
From the Service account dropdown, select New service account.
Enter a service account name and service account ID.
The name can be anything you want, but the account ID must be unique across all projects. DevConsole will generate a unique account ID for you, based on the name that you entered.
Select P12 for the key type, as shown below. P12 is required.
Click the Create button. DevConsole generates a private/public key pair for your project. The private key is saved to the default location that your browser stores downloads. You must download the
.p12format (binary), as opposed to the
You use the private key in your scripts or other applications that access the Travel Partner API.
DevConsole displays the following notice when it finishes generating the keys:
Click the OK, got it button. DevConsole returns you to the Credentials view. To confirm the details about your service account and see the service accounts associated with your project, click Manage service accounts in this view.
The service account now has the following credentials associated with it:
- Client ID: A unique identifier that your application uses when requesting an OAuth 2.0 access token.
- Email address: A generated email address for the service account, in the form "account_name@project_name.google.com.iam.gserviceaccount.com".
- Certificate fingerprints: The ID of the private key that you downloaded.
For more information, refer to Using OAuth 2.0 for Server to Server Applications.
Step 4: Give the service account access to your Hotel Center data
The final step is to provide the new service account with access to your Hotel Center. The service account is identified by the generated email address that you created in the previous step. You provide access to this account by using the Hotel Center sharing settings.
To give a service account access to your Hotel Center data:
If you do not have proper access to add users to the account, contact the Google Hotels team using the contact us form and request us to set up ownership for your account. You can request one or more emails to be made to an owner. For more information on Hotel Center access, refer to Link Hotel Center and Google Ads.
In a new browser window, open the Hotel Center.
On the Hotel Center by Google banner, click the add user icon to open the sharing dialog.
In the Add more people field, enter the email address of the service account you want to add to your Hotel Center.
Keep the Notify people option selected.
From the drop-down menu, select Manage.
Click the Invite button.
After you add users to your Hotel Center, your service account should be enabled for API access within about 24 hours.
After Google notifies you that API access is enabled for your service account, you can start accessing the API with OAuth.
Using OAuth 2.0
To access the API, your application must identify itself to Google with the
service account's generated email address and private key. Google's
authentication mechanism exchanges this key for an OAuth 2.0 access token that
you pass in the
Authorization header in your app's API calls.
Access tokens (also known as bearer tokens) are part of the OAuth 2.0 standard. The syntax for specifying an access token in an HTTP header is:
Authorization: Bearer *oauth2_access_token*
The following example shows sample HTTP headers of a request that accesses the Reports API:
GET /travelpartner/v2.0/42000042/reports/top_opportunity_7_day HTTP/1.1 Host: www.googleapis.com Authorization: Bearer nd42.fdLSKkljD98344444444444lSDF42fdLSKkljD98344444444444lSDF42 Cache-Control: no-cache
To generate an access token, create an application in any language you choose.
The following example generates the token in Python. You can then use this
token in your requests'
Authorization headers when accessing the Travel Partner API.
#!/usr/bin/python2.7 # """ Sample code to get an auth header that you can use in your HTTP requests 1. Please see https://developers.google.com/api-client-library/python/start/installation to download and install the google-api-python-client package. 2. Edit lines below marked _SERVICE_ACCOUNT, _KEY_FILE, _PARTNER_NAME, and _API_VERSION. 3. Run the program using: "python sample.py". The app returns the value that you use for the Authorization header's Bearer token in your request. 4. Copy the token and use it in requests to the Travel Partner API. For example (2.0): https://www.googleapis.com/travelpartner/2.0/42000042/reports/budget For example (1.x): https://www.googleapis.com/travelpartner/1.2/reports?report_type=BUDGET """ import httplib2 import json import os import sys import urllib HAS_CRYPTO = False from apiclient import discovery from oauth2client.client import flow_from_clientsecrets try: # Some systems may not have OpenSSL installed so can't use SignedJwtAssertionCredentials. from oauth2client.client import SignedJwtAssertionCredentials HAS_CRYPTO = True except ImportError: print "Unable to import SignedJwtAssertionCredentials" from oauth2client import tools from oauth2client.file import Storage # Authorization scope for our requests (do not change) _DEFAULT_APISCOPE = 'https://www.googleapis.com/auth/travelpartner' # Use the service account you set up in the Google Developers Platform. # It will be of the form "gsaccount_name@project_name.google.com.iam.gserviceaccount.com". _SERVICE_ACCOUNT = ('email@example.com') # Set this to the full path to your service account's private binary .p12 key file # that you downloaded from the Google Developer's Console and stored in a secure place. # DO NOT use the json version of the certificate. _KEY_FILE = '../mylocaldir/api-keys/8482bb2bdb08.p12' # Set this to the case-sensitive "Partner Key", NOT the account # name in the Hotel Ads Center or the numeric partner ID. # Check with your TAM if you do not know your "Partner Key" name. _PARTNER_NAME = 'testpartner2' class HotelAdsAPIConnection(object): def __init__(self, service_account=_SERVICE_ACCOUNT, key=_KEY_FILE, partner=_PARTNER_NAME): self.key_file = key self.account = service_account self.partner = partner def InitializeCredentials(self, scope): '''Get credentials for use in API requests. Generates service account credentials if the key file is present, and regular user credentials if the file is not found. ''' if os.path.exists(self.key_file): if not HAS_CRYPTO: raise Exception("Unable to use cryptographic functions " + "Try installing OpenSSL") with open (self.key_file, 'rb') as file: key = file.read(); creds = SignedJwtAssertionCredentials(self.account, key, scope) self.credentials = creds def authorize(self): '''Construct a HTTP client that uses the supplied credentials.''' return credentials.authorize(httplib2.Http()) def print_creds(self): '''Prints the Authorization header to use in HTTP requests.''' cred_dict = json.loads(self.credentials.to_json()) if 'access_token' in cred_dict: print 'Authorization: Bearer %s' % (cred_dict['access_token'],) else: print 'creds: %s' % (cred_dict,) def GetConnection(self): http = httplib2.Http() self.credentials.refresh(http) http = self.credentials.authorize(http) self.print_creds() return http def main(args): # Create an instance of the HotelAdsAPIConnection inner class api = HotelAdsAPIConnection() # Generate credentials api.InitializeCredentials(_DEFAULT_APISCOPE) # Output the Authorization header to use in HTTP requests api.GetConnection() if __name__ == "__main__": main(sys.argv)</pre>
When developing your application, be sure to follow the Best practices for securely using API keys.
The sample Python script outputs an
Authorization header's Bearer
token, as the following example shows:
$ python sample.py Authorization: Bearer ya29.42424242sample_420icu8122KSvoh4T42cRoG3rW1lc0Q $
Use the value of the token in your requests. It is good for 1 hour after you generate it.
Running into problems? Doing a quick check on the following items may solve the problem.
- Did you create a project in the Google Developer Console?
- Did you find and enable the Travel Partner API?
- Did you download a
.p12file—a private key after clicking Create client ID and selecting Service account?
- Did you get a service account client ID email address of a form:
- Did you shared your Hotel Ads Center account with the service account by clicking the Share this account button?
- Did you send the service account's email address and your partner ID to your Technical Account Manager (TAM)?
- Are your Travel Partner API calls passing a recently-obtained token in the
- Is your
Authorizationheader's Bearer token more than 1 hour old?
The following table lists some common errors and possible resolutions:
|Invalid credentials||This could mean a number of things. If you encounter this error, check that:
|Not found||Your endpoint is most likely malformed. Check that you are submitting a
|Invalid string value||One or more parts of the endpoint contains invalid syntax. For example, you might have misspelled part of the path. Check that you used the correct underscores, capitalization, and wording in your entire path.|
|Unsupported output format||This error most commonly occurs when using the Reports API. You must
|AccessTokenRefreshError/Invalid grant||When running the sample Python app, this error might be caused by
of the following:
|HotelAdsAPIConnection object has no attribute credentials||When running the sample Python app, the path to your
|Invalid scope||When running the sample Python app, the API scope must be
|Forbidden||The account ID that you use is one that you do not have authorization to access. If you are a sub-account owner, you might not be able to access the parent or root account ID.|