L'API Campaign Manager 360 fornisce accesso programmatico alle informazioni del tuo account Campaign Manager 360. Viene utilizzata per gestire e creare campagne e report, proprio come faresti tramite i servizi web Campaign Manager 360 e Report Builder.
Questa guida descrive come iniziare a utilizzare l'API Campaign Manager 360.
Prerequisiti
Prima di utilizzare l'API Campaign Manager 360, devi soddisfare alcuni passaggi preliminari:
Devi disporre di un account Campaign Manager 360. Per informazioni sulla registrazione, consulta la sezione Inserzionisti/Agenzie.
Il tuo account Campaign Manager 360 deve essere abilitato per l'accesso API. La maggior parte degli account ha questa opzione attivata per impostazione predefinita; se non ne hai la certezza, contatta il tuo rappresentante dell'account o il team di assistenza Campaign Manager 360 per ricevere aiuto.
Devi avere un profilo utente con accesso a questo account. Chiedi all'amministratore dell'account Campaign Manager 360 di creare un profilo utente associato a questo account.
Controlla le autorizzazioni del profilo utente nell'interfaccia utente di Campaign Manager 360. Questi controlli determinano a cosa può accedere il profilo utente dall'API. Non sono previste autorizzazioni API separate.
Crea un progetto
Per iniziare a utilizzare l'API Campaign Manager 360, devi prima creare o selezionare un progetto nella console API di Google e attivare l'API. L'utilizzo di questo link ti guida nella procedura e attiva automaticamente l'API Campaign Manager 360.
Genera credenziali
Tutte le richieste che invii all'API Campaign Manager 360 devono essere autorizzate. Per una breve panoramica dell'autorizzazione, leggi come autorizzare e identificare la tua applicazione su Google.
Le seguenti istruzioni ti guidano nella procedura di creazione di un ID client OAuth 2.0 da utilizzare con il flusso dell'applicazione installata. Per istruzioni sulla generazione delle credenziali da utilizzare con il flusso del service account, consulta la guida Service Account.
Segui i passaggi per configurare un progetto della console API di Google.
- Apri la pagina Credenziali nella console API.
Fai clic su CREA CREDENZIALI > ID client OAuth.
Se in precedenza non avevi configurato una schermata per il consenso OAuth per questo progetto, ti verrà chiesto di farlo ora. Fai clic su CONFIGURA SCHERMATA DI CONSENSO.
Seleziona il tipo di utente e fai clic su CREA.
Compila il modulo iniziale. Se necessario, puoi modificarlo in un secondo momento. Al termine, fai clic su Salva.
Torna a Credenziali > CREA CREDENZIALI > ID client OAuth per continuare.
Seleziona App desktop come tipo di applicazione, assegnale un nome e fai clic su Crea.
Al termine, ti verranno mostrati un ID client OAuth 2.0 e un client secret, che potrai scaricare in formato JSON e salvare per un utilizzo successivo.
Installare una libreria client
L'API Campaign Manager 360 si basa su HTTP e JSON, pertanto qualsiasi client HTTP standard può inviare richieste all'API e analizzare le risposte.
Tuttavia, le librerie client delle API di Google offrono una migliore integrazione del linguaggio, una maggiore sicurezza e supporto per effettuare richieste autorizzate. Le librerie client sono disponibili in più linguaggi di programmazione; utilizzandole puoi evitare di dover impostare le richieste HTTP e analizzare le risposte manualmente.
Per iniziare, seleziona il linguaggio di programmazione che stai utilizzando per lo sviluppo.
C#
Installa la libreria client dell'API Campaign Manager 360 per .NET più recente. Ti consigliamo di utilizzare NuGet per gestire l'installazione.
Apri la console di NuGet Package Manager ed esegui questo comando:
Install-Package Google.Apis.Dfareporting.v3_4
Scopri di più
Java
Installa la versione più recente della libreria client dell'API Campaign Manager 360 per Java. Ti consigliamo di utilizzare Maven per gestire l'installazione.
Aggiungi la seguente dipendenza al file pom.xml:
<dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-dfareporting</artifactId> <version>v4-rev20250722-2.0.0</version> <exclusions> <exclusion> <groupId>com.google.guava</groupId> <artifactId>guava-jdk5</artifactId> </exclusion> </exclusions> </dependency>
Scopri di più
PHP
Installa la più recente libreria client dell'API Campaign Manager 360 per PHP. Ti consigliamo di utilizzare Composer per gestire l'installazione.
Apri un terminale ed esegui questo comando:
composer require google/apiclient
Se hai già installato la libreria e vuoi solo eseguire l'aggiornamento all'ultima versione:
composer update google/apiclient
A seconda del sistema, potrebbe essere necessario anteporre a questi comandi
sudo.
Scopri di più
Python
Installa la più recente libreria client dell'API Campaign Manager 360 per Python. È consigliabile utilizzare pip per gestire l'installazione.
Apri un terminale ed esegui questo comando:
pip install --upgrade google-api-python-client
A seconda del sistema, potrebbe essere necessario anteporre a questi comandi
sudo.
Scopri di più
Ruby
Installa la più recente libreria client dell'API Campaign Manager 360 per Ruby. Ti consigliamo di utilizzare RubyGems per gestire l'installazione.
Apri un terminale ed esegui questo comando:
gem install google-api-client
Se hai già installato la libreria e vuoi solo eseguire l'aggiornamento all'ultima versione:
gem update -y google-api-client
A seconda del sistema, potrebbe essere necessario anteporre a questi comandi
sudo.
Scopri di più
Puoi trovare altre lingue supportate nella pagina Librerie client.
Fai una richiesta
Dopo aver creato le credenziali OAuth 2.0 e installato una libreria client, puoi iniziare a utilizzare l'API Campaign Manager 360. Scopri come autorizzare, configurare il client ed effettuare la prima richiesta seguendo la guida rapida riportata di seguito.
C#
Carica il file client secret e genera le credenziali di autorizzazione.
La prima volta che esegui questo passaggio, ti verrà chiesto di accettare una richiesta di autorizzazione nel browser. Prima di accettare, assicurati di aver eseguito l'accesso con un Account Google che abbia accesso a Campaign Manager 360. La tua applicazione sarà autorizzata ad accedere ai dati per conto dell'account attualmente connesso.
// Load client secrets from the specified JSON file. GoogleClientSecrets clientSecrets; using(Stream json = new FileStream(pathToJsonFile, FileMode.Open, FileAccess.Read)) { clientSecrets = GoogleClientSecrets.Load(json); } // Create an asynchronous authorization task. // // Note: providing a data store allows auth credentials to be cached, so they survive multiple // runs of the application. This avoids prompting the user for authorization every time the // access token expires, by remembering the refresh token. The "user" value is used to // identify a specific set of credentials within the data store. You may provide different // values here to persist credentials for multiple users to the same data store. Task<UserCredential> authorizationTask = GoogleWebAuthorizationBroker.AuthorizeAsync( clientSecrets.Secrets, OAuthScopes, "user", CancellationToken.None, dataStore); // Authorize and persist credentials to the data store. UserCredential credential = authorizationTask.Result;
Crea un client Dfareporting autorizzato.
// Create a Dfareporting service object. // // Note: application name should be replaced with a value that identifies your application. service = new DfareportingService( new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "C# installed app sample" } );
Esegui un'operazione.
// Retrieve and print all user profiles for the current authorized user. UserProfileList profiles = service.UserProfiles.List().Execute(); foreach (UserProfile profile in profiles.Items) { Console.WriteLine("Found user profile with ID {0} and name \"{1}\".", profile.ProfileId, profile.UserName); }
Java
Carica il file client secret e genera le credenziali di autorizzazione.
La prima volta che esegui questo passaggio, ti verrà chiesto di accettare una richiesta di autorizzazione nel browser. Prima di accettare, assicurati di aver eseguito l'accesso con un Account Google che abbia accesso a Campaign Manager 360. La tua applicazione sarà autorizzata ad accedere ai dati per conto dell'account attualmente connesso.
// Load the client secrets JSON file. GoogleClientSecrets clientSecrets = GoogleClientSecrets.load( jsonFactory, Files.newBufferedReader(Paths.get(pathToClientSecretsFile), UTF_8)); // Set up the authorization code flow. // // Note: providing a DataStoreFactory allows auth credentials to be cached, so they survive // multiple runs of the program. This avoids prompting the user for authorization every time the // access token expires, by remembering the refresh token. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( httpTransport, jsonFactory, clientSecrets, OAUTH_SCOPES) .setDataStoreFactory(dataStoreFactory) .build(); // Authorize and persist credentials to the data store. // // Note: the "user" value below is used to identify a specific set of credentials in the data // store. You may provide different values here to persist credentials for multiple users to // the same data store. Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
Crea un client Dfareporting autorizzato.
// Create a Dfareporting client instance. // // Note: application name below should be replaced with a value that identifies your // application. Suggested format is "MyCompany-ProductName/Version.MinorVersion". Dfareporting reporting = new Dfareporting.Builder(credential.getTransport(), credential.getJsonFactory(), credential) .setApplicationName("dfareporting-java-installed-app-sample") .build();
Esegui un'operazione.
// Retrieve and print all user profiles for the current authorized user. UserProfileList profiles = reporting.userProfiles().list().execute(); for (int i = 0; i < profiles.getItems().size(); i++) { System.out.printf("%d) %s%n", i + 1, profiles.getItems().get(i).getUserName()); }
PHP
Carica il file client secret e genera le credenziali di autorizzazione.
La prima volta che esegui questo passaggio, ti verrà chiesto di accettare una richiesta di autorizzazione nel browser. Prima di accettare, assicurati di aver eseguito l'accesso con un Account Google che abbia accesso a Campaign Manager 360. La tua applicazione sarà autorizzata ad accedere ai dati per conto dell'account attualmente connesso.
// Create a Google_Client instance. // // Note: application name should be replaced with a value that identifies // your application. Suggested format is "MyCompany-ProductName". $client = new Google_Client(); $client->setAccessType('offline'); $client->setApplicationName('PHP installed app sample'); $client->setRedirectUri(self::OAUTH_REDIRECT_URI); $client->setScopes(self::$OAUTH_SCOPES); // Load the client secrets file. $client->setAuthConfig($pathToJsonFile); // Try to load cached credentials from the token store. Using a token store // allows auth credentials to be cached, so they survive multiple runs of // the application. This avoids prompting the user for authorization every // time the access token expires, by remembering the refresh token. if (file_exists($tokenStore) && filesize($tokenStore) > 0) { $client->setAccessToken(file_get_contents($tokenStore)); } else { // If no cached credentials were found, authorize and persist // credentials to the token store. print 'Open this URL in your browser and authorize the application.'; printf("\n\n%s\n\n", $client->createAuthUrl()); print 'Enter the authorization code: '; $code = trim(fgets(STDIN)); $client->authenticate($code); file_put_contents($tokenStore, json_encode($client->getAccessToken())); }
Crea un client Dfareporting autorizzato.
// Create a Dfareporting service object. $service = new Google_Service_Dfareporting($client);
Esegui un'operazione.
// Retrieve and print all user profiles for the current authorized user. $result = $service->userProfiles->listUserProfiles(); foreach ($result['items'] as $userProfile) { printf( "User profile \"%s\" (ID: %d) found for account %d.\n", $userProfile->getUserName(), $userProfile->getProfileId(), $userProfile->getAccountId() ); }
Python
Carica il file client secret e genera le credenziali di autorizzazione.
La prima volta che esegui questo passaggio, ti verrà chiesto di accettare una richiesta di autorizzazione nel browser. Prima di accettare, assicurati di aver eseguito l'accesso con un Account Google che abbia accesso a Campaign Manager 360. La tua applicazione sarà autorizzata ad accedere ai dati per conto dell'account attualmente connesso.
# Set up a Flow object to be used if we need to authenticate. flow = client.flow_from_clientsecrets( path_to_client_secrets_file, scope=OAUTH_SCOPES) # Check whether credentials exist in the credential store. Using a credential # store allows auth credentials to be cached, so they survive multiple runs # of the application. This avoids prompting the user for authorization every # time the access token expires, by remembering the refresh token. storage = Storage(CREDENTIAL_STORE_FILE) credentials = storage.get() # If no credentials were found, go through the authorization process and # persist credentials to the credential store. if credentials is None or credentials.invalid: credentials = tools.run_flow(flow, storage, tools.argparser.parse_known_args()[0]) # Use the credentials to authorize an httplib2.Http instance. http = credentials.authorize(httplib2.Http())
Crea un client Dfareporting autorizzato.
# Construct a service object via the discovery service. service = discovery.build('dfareporting', 'v4', http=http)
Esegui un'operazione.
# Construct the request. request = service.userProfiles().list() # Execute request and print response. response = request.execute() for profile in response['items']: print('Found user profile with ID %s and user name "%s".' % (profile['profileId'], profile['userName']))
Ruby
Carica il file client secret e genera le credenziali di autorizzazione.
La prima volta che esegui questo passaggio, ti verrà chiesto di accettare una richiesta di autorizzazione nel browser. Prima di accettare, assicurati di aver eseguito l'accesso con un Account Google che abbia accesso a Campaign Manager 360. La tua applicazione sarà autorizzata ad accedere ai dati per conto dell'account attualmente connesso.
# Load client ID from the specified file. client_id = Google::Auth::ClientId.from_file(path_to_json_file) # Set up the user authorizer. # # Note: providing a token store allows auth credentials to be cached, so they # survive multiple runs of the application. This avoids prompting the user for # authorization every time the access token expires, by remembering the # refresh token. authorizer = Google::Auth::UserAuthorizer.new( client_id, [API_NAMESPACE::AUTH_DFAREPORTING], token_store ) # Authorize and persist credentials to the data store. # # Note: the 'user' value below is used to identify a specific set of # credentials in the token store. You may provide different values here to # persist credentials for multiple users to the same token store. authorization = authorizer.get_credentials('user') if authorization.nil? puts format( "Open this URL in your browser and authorize the application.\n\n%s" \ "\n\nEnter the authorization code:", authorizer.get_authorization_url(base_url: OAUTH_REDIRECT_URI) ) code = STDIN.gets.chomp authorization = authorizer.get_and_store_credentials_from_code( base_url: OAUTH_REDIRECT_URI, code: code, user_id: 'user' ) end
Crea un client Dfareporting autorizzato.
# Create a Dfareporting service object. # # Note: application name should be replaced with a value that identifies # your application. Suggested format is "MyCompany-ProductName". service = API_NAMESPACE::DfareportingService.new service.authorization = authorization service.client_options.application_name = 'Ruby installed app sample' service.client_options.application_version = '1.0.0'
Esegui un'operazione.
// Retrieve and print all user profiles for the current authorized user. UserProfileList profiles = service.UserProfiles.List().Execute(); foreach (UserProfile profile in profiles.Items) { Console.WriteLine("Found user profile with ID {0} and name \"{1}\".", profile.ProfileId, profile.UserName); }
Scopri di più
Visita il Riferimento API per scoprire tutti i servizi che l'API ha da offrire. Ogni pagina dei dettagli del metodo ha un API Explorer incorporato che puoi utilizzare per effettuare richieste di test direttamente dal browser.
Consulta le nostre altre guide, che trattano argomenti avanzati e forniscono esempi end-to-end per le attività comuni.
Quando è tutto pronto per iniziare a scrivere codice, non esitare a esplorare la nostra vasta raccolta di esempi di codice, che possono essere modificati ed estesi per soddisfare le tue esigenze.