Code Samples

The Google APIs Explorer dynamically generates code samples, which are designed to be copied and run locally. The samples update to reflect the parameter and property values you have entered in the tool. To see the samples, open the fullscreen APIs Explorer by clicking the icon in the APIs Explorer.

Screenshot of APIs Explorer with an arrow pointing to the icon that opens the fullscreen view of the Explorer.

By default, the APIs Explorer shows how to use cURL to execute your request. Some APIs might also show samples for other languages, such as JavaScript, Java, and Python.

Running code samples locally

The tabs below explain the prerequisites for running code samples in different languages. For any code sample, you will need your own API credentials, and some samples require OAuth 2.0 authorization. Your credentials will be one of the following, depending on the sample in question:

  • an API key
  • a client_secret.json file containing your OAuth 2.0 client ID and client secret
  • an OAuth 2.0 access token

If you run a sample that requires OAuth 2.0 authorization using only an API key, the API response will contain an error message indicating that the request is not properly authorized. Also, before trying to run a sample locally, look in the code sample for the strings TODO and YOUR. Code samples use those strings to identify changes that you need to make to run the sample successfully.

JavaScript
  1. Create or select a project in the API Console. Complete the following tasks in the API Console for your project:

    1. In the library panel, search for the API you are calling and make sure it is enabled for your project.

    2. In the credentials panel, either create an API key or create an OAuth 2.0 client ID and set the application type to web application. Note that some API requests require OAuth 2.0 authorization.

      If you created an OAuth 2.0 client ID, set the authorized JavaScript origins to identify the URL from which you'll be sending requests (e.g. http://localhost).

  2. Copy the full code sample to a local file accessible to your web server (e.g. /var/www/html/example.html).

  3. Find the line in the code sample that sets the API key or client ID to be used for the request, and replace the value with the appropriate value for your credentials:

    • API key
      gapi.client.setApiKey(YOUR_API_KEY);
    • OAuth 2.0 client ID
      gapi.client.init({
          'clientId': 'YOUR_CLIENT_ID',
  4. Open the file in your browser (e.g. http://localhost/example.html). It is recommended to use a browser with a debugging console, such as Google Chrome.

  5. Authorize the request if necessary. If the request is authorized, the debugging console should display the API response to the request as a JSON object.

Java

Prerequisites

  • Java 1.7 or greater
  • Gradle 2.3 or greater

Set up your project and run code samples

  1. Create or select a project in the API Console. Complete the following tasks in the API Console for your project:

    1. In the library panel, search for the API you are calling and make sure it is enabled for your project.

    2. In the credentials panel, either create an API key or create an OAuth 2.0 client ID and set the application type to Other. Note that some API requests require OAuth 2.0 authorization.

      If you created an OAuth 2.0 client ID, download the JSON file that contains your OAuth 2.0 credentials. The file has a name like client_secret_CLIENTID.json, where CLIENTID is the client ID for your project.

  2. Complete the following steps to prepare your Gradle project:

    1. In your working directory, run the following commands to create a new project structure:
      $ gradle init --type basic
      $ mkdir -p src/main/java src/main/resources 
      
    2. If you created an OAuth 2.0 client ID in step 1, rename the JSON file that you downloaded to client_secret.json. Save the renamed file in the src/main/resources directory that you created in step 2a. (If you name the file something else, you must also update the code sample to look for the right filename.)
    3. Open the build.gradle file in your working directory and replace its contents with the following:
    4. apply plugin: 'java'
      apply plugin: 'application'
      
      mainClassName = 'ApiExample'
      sourceCompatibility = 1.7
      targetCompatibility = 1.7
      version = '1.0'
      
      repositories {
          mavenCentral()
      }
      
      dependencies {
          compile 'com.google.api-client:google-api-client:1.23.0'
          compile 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'
          API_SPECIFIC_DEPENDENCY
      }
    5. In the build.gradle file, replace the line that says API_SPECIFIC_DEPENDENCY with an instruction to compile code for the API you are calling. Here is a sample for the YouTube Analytics API:
      compile 'com.google.apis:google-api-services-youtubeAnalytics:v2-rev16-1.23.0'

      The instruction follows this template:

      compile 'com.google.apis:google-api-services-API_NAME:API_VERSION-revREVISION-CL_VERSION'

      In that template:

      • API_NAME is the API name listed for the API on this page.
      • API_VERSION is the API version listed for the API below the API name on the same page.
      • REVISION is the revision number listed in the JavaDoc reference for the API. The JavaDoc reference can be found at https://developers.google.com/resources/api-libraries/documentation/API_NAME/API_VERSION/java/latest/. (Replace API_NAME and API_VERSION in the URL with the correct information.)
      • CL_VERSION is the client library version. It also appears in the JavaDoc reference. The screenshot below shows where the REVISION and CL_VERSION values appear in the JavaDoc for reference for the YouTube Analytics API:

        Screenshot of JavaDoc reference showing how to find values for 'REVISION' and 'CL_VERSION' variables.

  3. From your working directory, copy the code sample from APIs Explorer to src/main/java/ApiExample.java. (The class name in each sample is ApiExample so that you do not need to modify the build.gradle file to run different samples.)

  4. Run the sample from the command line:

    gradle -q run
  5. The sample should execute your API request and print the response to STDOUT. You can also check the service you are calling to see the effects of requests that write data.

Node.js

Prerequisites

  • Node.js and npm installed
  • The Google APIs Client Library for Node.js:
    • If you have not previously installed the client library:
      npm install googleapis --save
    • If you previously installed the client library, we recommend updating it to ensure that you have the most up-to-date classes for the library you are testing:
      npm update googleapis --save

Set up your project and run code samples

  1. Create or select a project in the API Console. Complete the following tasks in the API Console for your project:

    1. In the library panel, search for the API you are calling and make sure it is enabled for your project.

    2. In the credentials panel, either create an API key or create an OAuth 2.0 client ID and set the application type to Other. Note that some API requests require OAuth 2.0 authorization.

  2. Save the client secrets JSON file associated with your credentials to a local file, such as client_secret.json.

  3. Copy the full code sample to a local file and modify the sample to correctly identify your API key or client secrets file. In the sample, the API key value is YOUR_API_KEY, and the client secrets file location is YOUR_CLIENT_SECRET_FILE.json.

  4. Run the sample from the command line:

    node sample.js
  5. Most samples print an API response (or something else) to STDOUT.

PHP

Prerequisites

  • PHP 5.4 or greater with the command-line interface (CLI) and JSON extension installed.
  • The Composer dependency management tool installed globally.
  • The Google APIs Client Library for PHP:
    • If you have not previously installed the client library:
      composer require google/apiclient:^2.0
    • If you previously installed the client library, we recommend updating it to ensure that you have the most up-to-date classes for the library you are testing:
      composer update google/apiclient --with-dependencies

Set up your project and run code samples

  1. Create or select a project in the API Console. Complete the following tasks in the API Console for your project:

    1. In the library panel, search for the API you are calling and make sure it is enabled for your project.

    2. In the credentials panel, either create an API key or create an OAuth 2.0 client ID and set the application type to Other. Note that some API requests require OAuth 2.0 authorization.

  2. Save the client secrets JSON file associated with your credentials to a local file, such as client_secret.json.

  3. Copy the full code sample to a local file and modify the sample to correctly identify your API key or client secrets file. In the sample, the API key value is YOUR_API_KEY, and the client secrets file location is YOUR_CLIENT_SECRET_FILE.json.

  4. Run the sample from the command line:

    php sample.php
  5. Most samples print an API response (or something else) to STDOUT.

Python

Prerequisites

  • Python 2.7 or Python 3.5+
  • The pip package management tool
  • The Google APIs Client Library for Python:
    pip install --upgrade google-api-python-client
  • The google-auth-oauthlib and google-auth-httplib2 libraries for user authorization.
    pip install --upgrade google-auth-oauthlib google-auth-httplib2

Set up your project and run code samples

  1. Create or select a project in the API Console. Complete the following tasks in the API Console for your project:

    1. In the library panel, search for the API you are calling and make sure it is enabled for your project.

    2. In the credentials panel, either create an API key or create an OAuth 2.0 client ID and set the application type to Other. Note that some API requests require OAuth 2.0 authorization.

  2. Save the client secrets JSON file associated with your credentials to a local file, such as client_secret.json.

  3. Copy the full code sample to a local file and modify the sample to correctly identify your API key or client secrets file. In the sample, the API key value is YOUR_API_KEY, and the client secrets file location is YOUR_CLIENT_SECRET_FILE.json.

  4. Run the sample from the command line:

    python sample.py
  5. Most samples print an API response (or something else) to STDOUT.

Troubleshooting

This section explains how to troubleshoot some frequently reported issues. Most of these errors can occur when you execute requests in the APIs Explorer widget or if you test the APIs Explorer's code samples locally. To run samples locally, you must usually make at least one change to the sample, which is to update the code to identify the your API key or the local path to your client secrets file. However, sometimes additional changes are required as well.

Important: If you get an error when trying to locally run one of the code samples, start by looking in the sample for the strings TODO and YOUR. Code samples use that text to identify values that you need to set to run the sample successfully or other actions you need to take to run the sample successfully. Here are some examples:
  • YOUR_CLIENT_SECRET_FILE
  • YOUR_VIDEO_ID
  • TODO: For this request to work, you must replace "YOUR_FILE" with the path to the file where that content should be written.

Authorization and authentication errors

Every API request must use some type of credentials to identify the application that is calling the API and, depending on the request, the user who is making the request. If the API server needs to identify the user making the request and obtain their permission to complete the request, then that request requires user authorization. For example, if a request calls the Gmail API to retrieve your Gmail messages, the API server should only return those messages if you authorized the operation.

Your code can use an API key or an OAuth 2.0 client ID to identify your application. However, requests that require user authorization must use an OAuth 2.0 client ID.

When you try to execute an API request, the API server verifies a few different things before returning a result. If you are getting a 401 or 403 error when testing a sample, it is likely due to a problem at one of those steps. The following subsections explain several common causes of those errors. Note that 401 errors are often communicated as Unauthorized or Login Required, while 403 errors are often communicated as Forbidden or insufficientPermissions.

Note: The APIs Explorer uses demo credentials by default to make it easier to get started. But you need your own credentials to call APIs from your own code so that you have your own quota, permissions, etc.

Your code calls an API that isn't enabled for your project

In the API Console you need to enable your project to call different APIs. The API server usually returns a 403 error if you try to call an API that hasn't been enabled for your project. To enable an API, go to the API Library page in the API Console and find the API. The page that describes the API should display a button to enable it.

Credential restrictions prevent the request from being executed

When you create your API credentials, you can set restrictions to help prevent unauthorized use of your credentials and, hence, your API quota. For example, you can specify authorized HTTP referrers, IP addresses, JavaScript origins, Android package names, and redirect URIs. The API server uses that information to confirm that a request that's using your credentials is actually coming from your application.

If you place restrictions on your API credentials, then a request that uses those credentials must meet those restrictions. For example, if you specify valid JavaScript origins, then any request that uses your API credentials must originate from one of those locations. The API server usually returns a 403 error if a request uses API credentials that specify restrictions but the request doesn't meet those restrictions.

Request specifies API key, but requires OAuth 2.0 client ID

Many API requests require an authenticated user to authorize the request. For example, an API request that uploads a YouTube video must be authorized by the user whose channel the video is being uploaded to. Requests that require user authorization must use an OAuth 2.0 client ID.

If your request requires user authorization but only specifies an API key, the API server usually returns a 401 error because the request cannot be completed without permission from the user making the request. Using the example from the previous paragraph, you can't upload a video to your YouTube channel if the API server can't securely figure out who you are.

Google uses your OAuth 2.0 client ID during the authorization process to obtain a token that identifies the user. That identification can't be made using only an API key.

User has not granted the permissions needed for the request

When an application makes a request that requires user authorization, the user must have also granted the application permission to make that request. Permissions are requested using scopes. The API server usually returns a 403 (Insufficient Permission) error if the authorization credentials do not cover the scopes required for the request.

For example, suppose you send an API request that lists your Google Drive files. For that request, you need to grant the application making the request permission to read data from Google Drive.

Then, you make a second request to retrieve data about events in your Google Calendar. The second request accesses different data and requires different permissions than the first request. If you try to use the same authorization credentials as in the first request, the second request returns an error.

Your request is authorized by the wrong user

An application doesn't just need permission from any user to complete a request. Rather, it needs permission from someone who is actually authorized to grant that permission. For example, you can't authorize a request to retrieve someone else's Gmail messages.

The API server usually returns a 403 (Forbidden) error if a request is authorized by one user but should be authorized by a different user.

Language-specific errors

JavaScript

  • gapi is not defined

    This error occurs when your JavaScript code tries to call the Google API Client Library for JavaScript before the library has actually loaded. Make sure that your code that references the gapi variable is not called until after the client library has loaded.

    The examples for loading an API and making a request and for loading the client library asynchronously show two different ways to make sure the library is loaded before your code starts calling it.