Method: instances.list

Lists instances under a given project.

HTTP request

GET https://sqladmin.googleapis.com/sql/v1beta4/projects/{project}/instances

The URL uses gRPC Transcoding syntax.

Path parameters

Parameters
project

string

Project ID of the project for which to list Cloud SQL instances.

Query parameters

Parameters
filter

string

A filter expression that filters resources listed in the response. The expression is in the form of field:value. For example, 'instanceType:CLOUD_SQL_INSTANCE'. Fields can be nested as needed as per their JSON representation, such as 'settings.userLabels.auto_start:true'.

Multiple filter queries are space-separated. For example. 'state:RUNNABLE instanceType:CLOUD_SQL_INSTANCE'. By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly.

maxResults

integer (uint32 format)

The maximum number of instances to return. The service may return fewer than this value. If unspecified, at most 500 instances are returned. The maximum value is 1000; values above 1000 are coerced to 1000.

pageToken

string

A previously-returned page token representing part of the larger set of results to view.

Request body

The request body must be empty.

Response body

If successful, the response body contains data with the following structure:

Database instances list response.

JSON representation
{
  "kind": string,
  "warnings": [
    {
      object (ApiWarning)
    }
  ],
  "items": [
    {
      object (DatabaseInstance)
    }
  ],
  "nextPageToken": string
}
Fields
kind

string

This is always sql#instancesList.

warnings[]

object (ApiWarning)

instances.list of warnings that occurred while handling the request.

items[]

object (DatabaseInstance)

instances.list of database instance resources.

nextPageToken

string

The continuation token, used to page through large result sets. Provide this value in a subsequent request to return the next page of results.

Authorization Scopes

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/cloud-platform
  • https://www.googleapis.com/auth/sqlservice.admin

For more information, see the Authentication Overview.

ApiWarning

An Admin API warning message.

JSON representation
{
  "code": enum (SqlApiWarningCode),
  "message": string,
  "region": string
}
Fields
code

enum (SqlApiWarningCode)

Code to uniquely identify the warning type.

message

string

The warning message.

region

string

The region name for REGION_UNREACHABLE warning.

SqlApiWarningCode

Enums
SQL_API_WARNING_CODE_UNSPECIFIED An unknown or unset warning type from Cloud SQL API.
REGION_UNREACHABLE Warning when one or more regions are not reachable. The returned result set may be incomplete.
MAX_RESULTS_EXCEEDS_LIMIT Warning when user provided maxResults parameter exceeds the limit. The returned result set may be incomplete.

Examples

Uses the .NET client library.

// BEFORE RUNNING:
// ---------------
// 1. If not already done, enable the Cloud SQL Administration API
//    and check the quota for your project at
//    https://console.developers.google.com/apis/api/sqladmin
// 2. This sample uses Application Default Credentials for authentication.
//    If not already done, install the gcloud CLI from
//    https://cloud.google.com/sdk and run
//    `gcloud beta auth application-default login`.
//    For more information, see
//    https://developers.google.com/identity/protocols/application-default-credentials
// 3. Install the C# client library by adding a dependency on the relevant NuGet
//    package. Libraries published by Google are owned by google-apis-packages:
//    https://www.nuget.org/profiles/google-apis-packages

using Google.Apis.Auth.OAuth2;
using Google.Apis.SQLAdmin.v1beta4;
using Google.Apis.Services;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;

using Data = Google.Apis.SQLAdmin.v1beta4.Data;

namespace SQLAdminSample
{
   
public class SQLAdminExample
   
{
       
public static void Main(string[] args)
       
{
           
SQLAdminService sqlAdminService = new SQLAdminService(new BaseClientService.Initializer
           
{
               
HttpClientInitializer = GetCredential(),
               
ApplicationName = "Google-SQLAdminSample/0.1",
           
});

           
// Project ID of the project for which to list Cloud SQL instances.
           
string project = "my-project";  // TODO: Update placeholder value.

           
InstancesResource.ListRequest request = sqlAdminService.Instances.List(project);

           
Data.InstancesListResponse response;
           
do
           
{
               
// To execute asynchronously in an async method, replace `request.Execute()` as shown:
                response
= request.Execute();
               
// response = await request.ExecuteAsync();

               
if (response.Items == null)
               
{
                   
continue;
               
}
               
foreach (Data.DatabaseInstance databaseInstance in response.Items)
               
{
                   
// TODO: Change code below to process each `databaseInstance` resource:
                   
Console.WriteLine(JsonConvert.SerializeObject(databaseInstance));
               
}
                request
.PageToken = response.NextPageToken;
           
} while (response.NextPageToken != null);
       
}

       
public static GoogleCredential GetCredential()
       
{
           
GoogleCredential credential = Task.Run(() => GoogleCredential.GetApplicationDefaultAsync()).Result;
           
if (credential.IsCreateScopedRequired)
           
{
                credential
= credential.CreateScoped("https://www.googleapis.com/auth/cloud-platform");
           
}
           
return credential;
       
}
   
}
}

Uses the Go client library.

package main

// BEFORE RUNNING:
// ---------------
// 1. If not already done, enable the Cloud SQL Administration API
//    and check the quota for your project at
//    https://console.developers.google.com/apis/api/sqladmin
// 2. This sample uses Application Default Credentials for authentication.
//    If not already done, install the gcloud CLI from
//    https://cloud.google.com/sdk/ and run
//    `gcloud beta auth application-default login`.
//    For more information, see
//    https://developers.google.com/identity/protocols/application-default-credentials
// 3. Install and update the Go dependencies by running `go get -u` in the
//    project directory.

import (
       
"fmt"
       
"log"

       
"golang.org/x/net/context"
       
"golang.org/x/oauth2/google"
       
"google.golang.org/api/sqladmin/v1beta4"
)

func main
() {
        ctx
:= context.Background()

        c
, err := google.DefaultClient(ctx, sqladmin.CloudPlatformScope)
       
if err != nil {
                log
.Fatal(err)
       
}

        sqladminService
, err := sqladmin.New(c)
       
if err != nil {
                log
.Fatal(err)
       
}

       
// Project ID of the project for which to list Cloud SQL instances.
        project
:= "my-project" // TODO: Update placeholder value.

        req
:= sqladminService.Instances.List(project)
       
if err := req.Pages(ctx, func(page *sqladmin.InstancesListResponse) error {
               
for _, databaseInstance := range page.Items {
                       
// TODO: Change code below to process each `databaseInstance` resource:
                        fmt
.Printf("%#v\n", databaseInstance)
               
}
               
return nil
       
}); err != nil {
                log
.Fatal(err)
       
}
}

Uses the Java client library.

/*
 * BEFORE RUNNING:
 * ---------------
 * 1. If not already done, enable the Cloud SQL Administration API
 *    and check the quota for your project at
 *    https://console.developers.google.com/apis/api/sqladmin
 * 2. This sample uses Application Default Credentials for authentication.
 *    If not already done, install the gcloud CLI from
 *    https://cloud.google.com/sdk and run
 *    `gcloud beta auth application-default login`.
 *    For more information, see
 *    https://developers.google.com/identity/protocols/application-default-credentials
 * 3. Install the Java client library on Maven or Gradle. Check installation
 *    instructions at https://github.com/google/google-api-java-client.
 *    On other build systems, you can add the jar files to your project from
 *    https://developers.google.com/resources/api-libraries/download/sqladmin/v1beta4/java
 */


import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.sqladmin.SQLAdmin;
import com.google.api.services.sqladmin.model.DatabaseInstance;
import com.google.api.services.sqladmin.model.InstancesListResponse;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;

public class SqlAdminExample {
 
public static void main(String args[]) throws IOException, GeneralSecurityException {
   
// Project ID of the project for which to list Cloud SQL instances.
   
String project = "my-project"; // TODO: Update placeholder value.

   
SQLAdmin sqlAdminService = createSqlAdminService();
   
SQLAdmin.Instances.List request = sqlAdminService.instances().list(project);

   
InstancesListResponse response;
   
do {
      response
= request.execute();
     
if (response.getItems() == null) {
       
continue;
     
}
     
for (DatabaseInstance databaseInstance : response.getItems()) {
       
// TODO: Change code below to process each `databaseInstance` resource:
       
System.out.println(databaseInstance);
     
}
      request
.setPageToken(response.getNextPageToken());
   
} while (response.getNextPageToken() != null);
 
}

 
public static SQLAdmin createSqlAdminService() throws IOException, GeneralSecurityException {
   
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
   
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

   
GoogleCredential credential = GoogleCredential.getApplicationDefault();
   
if (credential.createScopedRequired()) {
      credential
=
          credential
.createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
   
}

   
return new SQLAdmin.Builder(httpTransport, jsonFactory, credential)
       
.setApplicationName("Google-SQLAdminSample/0.1")
       
.build();
 
}
}

Uses the Node.js client library.

// BEFORE RUNNING:
// ---------------
// 1. If not already done, enable the Cloud SQL Admin API
//    and check the quota for your project at
//    https://console.developers.google.com/apis/api/sqladmin
// 2. This sample uses Application Default Credentials for authentication.
//    If not already done, install the gcloud CLI from
//    https://cloud.google.com/sdk and run
//    `gcloud beta auth application-default login`.
//    For more information, see
//    https://developers.google.com/identity/protocols/application-default-credentials
// 3. Install the Node.js client library by running
//    `npm install googleapis --save`

const {google} = require('googleapis');
var sqlAdmin = google.sqladmin('v1beta4');

authorize
(function(authClient) {
 
var request = {
   
// Project ID of the project for which to list Cloud SQL instances.
    project
: 'my-project',  // TODO: Update placeholder value.

    auth
: authClient,
 
};

 
var handlePage = function(err, response) {
   
if (err) {
      console
.error(err);
     
return;
   
}

   
var itemsPage = response['items'];
   
if (!itemsPage) {
     
return;
   
}
   
for (var i = 0; i < itemsPage.length; i++) {
     
// TODO: Change code below to process each resource in `itemsPage`:
      console
.log(JSON.stringify(itemsPage[i], null, 2));
   
}

   
if (response.nextPageToken) {
      request
.pageToken = response.nextPageToken;
      sqlAdmin
.instances.list(request, handlePage);
   
}
 
};

  sqlAdmin
.instances.list(request, handlePage);
});

function authorize(callback) {
  google
.auth.getClient({
    scopes
: ['https://www.googleapis.com/auth/cloud-platform']
 
}).then(client => {
    callback
(client);
 
}).catch(err => {
    console
.error('authentication failed: ', err);
 
});
}

Uses the PHP client library.

<?php
/*
 * BEFORE RUNNING:
 * ---------------
 * 1. If not already done, enable the Cloud SQL Administration API
 *    and check the quota for your project at
 *    https://console.developers.google.com/apis/api/sqladmin
 * 2. This sample uses Application Default Credentials for authentication.
 *    If not already done, install the gcloud CLI from
 *    https://cloud.google.com/sdk and run
 *    `gcloud beta auth application-default login`.
 *    For more information, see
 *    https://developers.google.com/identity/protocols/application-default-credentials
 * 3. Install the PHP client library with Composer. Check installation
 *    instructions at https://github.com/google/google-api-php-client.
 */


// Autoload Composer.
require_once __DIR__
. '/vendor/autoload.php';

$client
= new Google_Client();
$client
->setApplicationName('Google-SQLAdminSample/0.1');
$client
->useApplicationDefaultCredentials();
$client
->addScope('https://www.googleapis.com/auth/cloud-platform');

$service
= new Google_Service_SQLAdmin($client);

// Project ID of the project for which to list Cloud SQL instances.
$project
= 'my-project';  // TODO: Update placeholder value.

$optParams
= [];

do {
  $response
= $service->instances->listInstances($project, $optParams);

 
foreach ($response['items'] as $databaseInstance) {
   
// TODO: Change code below to process each `databaseInstance` resource:
    echo
'<pre>', var_export($databaseInstance, true), '</pre>', "\n";
 
}

  $optParams
['pageToken'] = $response->getNextPageToken();
} while ($optParams['pageToken']);
?>

Uses the Python client library.

"""
BEFORE RUNNING:
---------------
1. If not already done, enable the Cloud SQL Administration API
   and check the quota for your project at
   https://console.developers.google.com/apis/api/sqladmin
2. This sample uses Application Default Credentials for authentication.
   If not already done, install the gcloud CLI from
   https://cloud.google.com/sdk and run
   `gcloud beta auth application-default login`.
   For more information, see
   https://developers.google.com/identity/protocols/application-default-credentials
3. Install the Python client library for Google APIs by running
   `pip install --upgrade google-api-python-client`
"""

from pprint import pprint

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials

credentials
= GoogleCredentials.get_application_default()

service
= discovery.build('sqladmin', 'v1beta4', credentials=credentials)

# Project ID of the project for which to list Cloud SQL instances.
project
= 'my-project'  # TODO: Update placeholder value.

request
= service.instances().list(project=project)
while request is not None:
    response
= request.execute()

   
for database_instance in response['items']:
       
# TODO: Change code below to process each `database_instance` resource:
        pprint
(database_instance)

    request
= service.instances().list_next(previous_request=request, previous_response=response)

Uses the Ruby client library.

# BEFORE RUNNING:
# ---------------
# 1. If not already done, enable the Cloud SQL Administration API
#    and check the quota for your project at
#    https://console.developers.google.com/apis/api/sqladmin
# 2. This sample uses Application Default Credentials for authentication.
#    If not already done, install the gcloud CLI from
#    https://cloud.google.com/sdk and run
#    `gcloud beta auth application-default login`.
#    For more information, see
#    https://developers.google.com/identity/protocols/application-default-credentials
# 3. Install the Ruby client library and Application Default Credentials
#    library by running `gem install google-api-client` and
#    `gem install googleauth`

require 'googleauth'
require 'google/apis/sqladmin_v1beta4'

service
= Google::Apis::SqladminV1beta4::SqlAdminService.new

service
.authorization = \
   
Google::Auth.get_application_default(['https://www.googleapis.com/auth/cloud-platform'])

# Project ID of the project for which to list Cloud SQL instances.
project
= 'my-project'  # TODO: Update placeholder value.

items
= service.fetch_all do |token|
  service
.list_instances(project, page_token: token)
end

items
.each do |database_instance|
 
# TODO: Change code below to process each `database_instance` resource:
  puts database_instance
.to_json
end