Repository Public
1The easiest way to authenticate to the Gemini API is to configure an API2key, as described in the [Gemini API get started3guide](https://ai.google.dev/gemini-api/docs/get-started). If you need stricter access controls,4you can use OAuth instead. This guide will help5you set up authentication with OAuth.67This guide uses a simplified authentication approach that is appropriate8for a testing environment. For a production environment, learn9about10[authentication and authorization](https://developers.google.com/workspace/guides/auth-overview)11before12[choosing the access credentials](https://developers.google.com/workspace/guides/create-credentials#choose_the_access_credential_that_is_right_for_you)13that are appropriate for your app.1415## Objectives1617- Set up your cloud project for OAuth18- Set up application-default-credentials19- Manage credentials in your program instead of using `gcloud auth`2021## Prerequisites2223To run this quickstart, you need:2425- [A Google Cloud project](https://developers.google.com/workspace/guides/create-project)26- [A local installation of the gcloud CLI](https://cloud.google.com/sdk/docs/install)2728## Set up your cloud project2930To complete this quickstart, you first need to setup your Cloud project.3132### 1. Enable the API3334Before using Google APIs, you need to turn them on in a Google Cloud project.3536- In the Google Cloud console, enable the Google Generative Language API. 3738 [Enable the API](https://console.cloud.google.com/flows/enableapi?apiid=generativelanguage.googleapis.com)3940### 2. Configure the OAuth consent screen4142Next configure the project's OAuth consent screen and add yourself as a test43user. If you've already completed this step for your Cloud project, skip to the44next section.45461. In the Google Cloud console, go to **Menu** \>47 **Google Auth platform** \> **Overview**.4849 [Go to the Google Auth platform](https://console.developers.google.com/auth/overview)502. Complete the project configuration form and set the user type to **External**51 in the **Audience** section.52533. Complete the rest of the form, accept the User Data Policy terms, and then54 click **Create**.55564. For now, you can skip adding scopes and click **Save and Continue**. In the57 future, when you create an app for use outside of your Google Workspace58 organization, you must add and verify the authorization scopes that your59 app requires.60615. Add test users:6263 1. Navigate to the [Audience page](https://console.developers.google.com/auth/audience) of the Google Auth platform.64 2. Under **Test users** , click **Add users**.65 3. Enter your email address and any other authorized test users, then click **Save**.6667### 3. Authorize credentials for a desktop application6869To authenticate as an end user and access user data in your app, you need to70create one or more OAuth 2.0 Client IDs. A client ID is used to identify a71single app to Google's OAuth servers. If your app runs on multiple platforms,72you must create a separate client ID for each platform.73741. In the Google Cloud console, go to **Menu** \> **Google Auth platform** \>75 **Clients**.7677 [Go to Credentials](https://console.developers.google.com/auth/clients)782. Click **Create Client**.79803. Click **Application type** \> **Desktop app**.81824. In the **Name** field, type a name for the credential. This name is only83 shown in the Google Cloud console.84855. Click **Create**. The OAuth client created screen appears, showing your new86 Client ID and Client secret.87886. Click **OK** . The newly created credential appears under **OAuth 2.0 Client89 IDs.**90917. Click the download button to save the JSON file. It will be saved as92 `client_secret_<identifier>.json`, and rename it to `client_secret.json`93 and move it to your working directory.9495## Set up Application Default Credentials9697To convert the `client_secret.json` file into usable credentials, pass its98location the `gcloud auth application-default login` command's99`--client-id-file` argument.100101 gcloud auth application-default login \102 --client-id-file=client_secret.json \103 --scopes='https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/generative-language.retriever'104105The simplified project setup in this tutorial triggers a **"Google hasn't106verified this app."** dialog. This is normal, choose **"continue"**.107108This places the resulting token in a well known location so it can be accessed109by `gcloud` or the client libraries.110111> [!NOTE]112> **Note:** If running on Colab include `--no-browser` and carefully follow the instructions it prints (don't just click the link). Also make sure your local `gcloud --version` is the [latest](https://cloud.google.com/sdk/docs/release-notes) to match Colab.113114 gcloud auth application-default login 115116 --no-browser117 --client-id-file=client_secret.json 118119 --scopes='https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/generative-language.retriever'120121<br />122123Once you have the Application Default Credentials (ADC) set, the client124libraries in most languages need minimal to no help to find them.125126### Curl127128The quickest way to test that this is working is to use it to access the REST129API using curl:130131 access_token=$(gcloud auth application-default print-access-token)132 project_id=<MY PROJECT ID>133 curl -X GET https://generativelanguage.googleapis.com/v1/models \134 -H 'Content-Type: application/json' \135 -H "Authorization: Bearer ${access_token}" \136 -H "x-goog-user-project: ${project_id}" | grep '"name"'137138### Python139140In python the client libraries should find them automatically:141142 pip install google-genai143144A minimal script to test it might be:145146 from google import genai147148 client = genai.Client()149 print('Available base models:', [m.name for m in client.models.list()])150151## Manage credentials yourself \[Python\]152153In many cases you won't have the `gcloud` command available to create the access154token from the Client ID (`client_secret.json`). Google provides libraries in155many languages to let you manage that process within your app. This section156demonstrates the process, in python. There are equivalent examples of this sort157of procedure, for other languages, available in the158[Drive API documentation](https://developers.google.com/drive/api/quickstart/python)159160### 1. Install the necessary libraries161162Install the Google client library for Python, and the Gemini client library.163164 pip install --upgrade -q google-api-python-client google-auth-httplib2 google-auth-oauthlib165 pip install google-genai166167### 2. Write the credential manager168169To minimize the number of times you have to click through the authorization170screens, create a file called `load_creds.py` in your working directory to171caches a `token.json` file that it can reuse later, or refresh if it expires.172173Start with the174following code to convert the `client_secret.json` file to a token usable with175`genai.configure`:176177 import os.path178179 from google.auth.transport.requests import Request180 from google.oauth2.credentials import Credentials181 from google_auth_oauthlib.flow import InstalledAppFlow182183 SCOPES = ['https://www.googleapis.com/auth/generative-language.retriever']184185 def load_creds():186 """Converts `client_secret.json` to a credential object.187188 This function caches the generated tokens to minimize the use of the189 consent screen.190 """191 creds = None192 # The file token.json stores the user's access and refresh tokens, and is193 # created automatically when the authorization flow completes for the first194 # time.195 if os.path.exists('token.json'):196 creds = Credentials.from_authorized_user_file('token.json', SCOPES)197 # If there are no (valid) credentials available, let the user log in.198 if not creds or not creds.valid:199 if creds and creds.expired and creds.refresh_token:200 creds.refresh(Request())201 else:202 flow = InstalledAppFlow.from_client_secrets_file(203 'client_secret.json', SCOPES)204 creds = flow.run_local_server(port=0)205 # Save the credentials for the next run206 with open('token.json', 'w') as token:207 token.write(creds.to_json())208 return creds209210### 3. Write your program211212Now create your `script.py`:213214 import pprint215 from google import genai216 from load_creds import load_creds217218 creds = load_creds()219220 client = genai.Client(credentials=creds)221222 print()223 print('Available base models:', [m.name for m in client.models.list()])224225### 4. Run your program226227In your working directory, run the sample:228229 python script.py230231The first time you run the script, it opens a browser window and prompts you232to authorize access.2332341. If you're not already signed in to your Google Account, you're prompted to235 sign in. If you're signed in to multiple accounts, **be sure to select the236 account you set as a "Test Account" when configuring your project.**237238 > [!NOTE]239 > **Note:** The simplified project setup in this tutorial triggers a **"Google240 > hasn't verified this app."** dialog. This is normal, choose **"continue"**.2412422. Authorization information is stored in the file system, so the next time you243 run the sample code, you aren't prompted for authorization.244245You have successfully setup authentication.