Contacts: insert

Richiede l'autorizzazione

Inserisce un nuovo contatto. Vedi un esempio.

Richiesta

Richiesta HTTP

POST https://www.googleapis.com/mirror/v1/contacts

Autorizzazione

Questa richiesta richiede l'autorizzazione con il seguente ambito (scopri di più su autenticazione e autorizzazione).

Ambito
https://www.googleapis.com/auth/glass.timeline

Corpo della richiesta

Nel corpo della richiesta, fornisci una risorsa Contatti con le seguenti proprietà:

Nome proprietà Valore Descrizione Note
Proprietà obbligatorie
acceptCommands[].type string Il tipo di operazione a cui corrisponde questo comando. I valori consentiti sono:
  • TAKE_A_NOTE: consente di condividere un elemento della sequenza temporale con la trascrizione del parlato dell'utente dal comando del menu vocale "Scrivi una nota".
  • POST_AN_UPDATE: consente di condividere un elemento della sequenza temporale con la trascrizione del parlato dell'utente dal comando del menu vocale "Pubblica un aggiornamento".
accessibile in scrittura
displayName string Il nome da visualizzare per questo contatto. accessibile in scrittura
id string Un ID per questo contatto. Viene generato dall'applicazione e viene considerato come un token opaco. accessibile in scrittura
imageUrls[] list Insieme di URL immagine da visualizzare per un contatto. La maggior parte dei contatti avrà una sola immagine, ma un contatto di "gruppo" può includere fino a 8 URL immagine, che verranno ridimensionati e ritagliati in un mosaico nel client. accessibile in scrittura
Proprietà facoltative
acceptCommands[] list Un elenco di comandi del menu vocale che un contatto può gestire. Glass mostra fino a tre contatti per ogni comando del menu vocale. Se sono più numerosi, vengono mostrati i tre contatti con il valore priority più alto per quel determinato comando. accessibile in scrittura
acceptTypes[] list Un elenco dei tipi MIME supportati da un contatto. Il contatto verrà mostrato all'utente se uno qualsiasi dei suoi acceptTypes corrisponde a uno qualsiasi dei tipi di allegati nell'elemento. Se non viene fornito alcun valoreacceptTypes, il contatto verrà mostrato per tutti gli elementi. accessibile in scrittura
phoneNumber string Numero di telefono principale del contatto. Può essere un numero completo, con prefisso internazionale e prefisso, o un numero locale. accessibile in scrittura
priority unsigned integer Priorità del contatto per determinare l'ordine in un elenco di contatti. I contatti con priorità più alte verranno visualizzati prima di quelli con priorità più bassa. accessibile in scrittura
speakableName string Nome di questo contatto come deve essere pronunciato. Se il nome di questo contatto deve essere pronunciato nell'ambito di un menu di disambiguazione della voce, questo nome viene utilizzato come pronuncia prevista. È utile per i nomi dei contatti con caratteri non pronunciabili o la cui ortografia viene visualizzata altrimenti non fonetica. accessibile in scrittura
type string Il tipo di questo contatto. Viene utilizzato per l'ordinamento nelle UI. I valori consentiti sono:
  • INDIVIDUAL: rappresenta una singola persona. Questa è l'impostazione predefinita.
  • GROUP: rappresenta più di una persona.
accessibile in scrittura

Risposta

In caso di esito positivo, questo metodo restituisce una risorsa Contatti nel corpo della risposta.

Esempi

Nota: gli esempi di codice disponibili per questo metodo non rappresentano tutti i linguaggi di programmazione supportati (consulta la pagina relativa alle librerie client per un elenco dei linguaggi supportati).

Java

Utilizza la libreria client Java.

import com.google.api.services.mirror.Mirror;
import com.google.api.services.mirror.model.Contact;

import java.io.IOException;
import java.util.Arrays;

public class MyClass {
  // ...

  /**
   * Insert a new contact for the current user.
   * 
   * @param service Authorized Mirror service.
   * @param contactId ID of the contact to insert.
   * @param displayName Display name for the contact to insert.
   * @param iconUrl URL of the contact's icon.
   * @return The inserted contact on success, {@code null} otherwise.
   */
  public static Contact insertContact(Mirror service, String contactId, String displayName,
      String iconUrl) {
    Contact contact = new Contact();
    contact.setId(contactId);
    contact.setDisplayName(displayName);
    contact.setImageUrls(Arrays.asList(iconUrl));

    try {
      return service.contacts().insert(contact).execute();
    } catch (IOException e) {
      System.err.println("An error occurred: " + e);
      return null;
    }
  }

  // ...
}

.NET

Utilizza la libreria client.NET.

using System;
using System.Collections.Generic;

using Google.Apis.Mirror.v1;
using Google.Apis.Mirror.v1.Data;

public class MyClass {
  // ...

  /// <summary>
  /// Insert a new contact for the current user.
  /// </summary>
  /// <param name='service'>Authorized Mirror service.</param>
  /// <param name='contactId'>ID of the contact to insert.</param>
  /// <param name='displayName'>
  /// Display name for the contact to insert.
  /// </param>
  /// <param name='iconUrl'>URL of the contact's icon.</param>
  /// <returns>
  /// The inserted contact on success, null otherwise.
  /// </returns>
  public static Contact InsertContact(MirrorService service,
      String contactId, String displayName, String iconUrl) {
    Contact contact = new Contact() {
      Id = contactId,
      DisplayName = displayName,
      ImageUrls = new List<String>() {iconUrl}
    };
    try {
      return service.Contacts.Insert(contact).Fetch();
    } catch (Exception e) {
      Console.WriteLine("An error occurred: " + e.Message);
      return null;
    }
  }

  // ...
}

PHP

Utilizza la libreria client PHP.

/**
 * Insert a new contact for the current user.
 *
 * @param Google_MirrorService $service Authorized Mirror service.
 * @param string $contactId ID of the contact to insert.
 * @param string $displayName Display name for the contact to insert.
 * @param string $iconUrl URL of the contact's icon.
 * @return Google_Contact The inserted contact on success, null otherwise.
 */
function insertContact($service, $contactId, $displayName, $iconUrl) {
  try {
    $contact = new Google_Contact();
    $contact->setId($contactId);
    $contact->setDisplayName($displayName);
    $contact->setImageUrls(array($iconUrl));
    return $service->contacts->insert($contact);
  } catch (Exception $e) {
    print 'An error occurred: ' . $e->getMessage();
    return null;
  }
}

Python

Utilizza la libreria client Python.

from apiclient import errors
# ...

def insert_contact(service, contact_id, display_name, icon_url):
  """Insert a new contact for the current user.

  Args:
    service: Authorized Mirror service.
    contact_id: ID of the contact to insert.
    display_name: Display name for the contact to insert.
    icon_url: URL of the contact's icon.
  Returns:
    The inserted contact on success, None otherwise.
  """
  contact = {
      'id': contact_id,
      'displayName': display_name,
      'imageUrls': [icon_url]
  }
  try:
    service.contacts().insert(body=contact).execute()
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
    return None

Ruby

Utilizza la libreria client Ruby.

##
# Insert a new contact for the current user.
#
# @param [Google::APIClient] client
#   Authorized client instance.
# @param [String] contact_id
#   ID of the contact to insert.
# @param [String] display_name
#   Display name for the contact to insert.
# @param [String] image_url
#   URL of the contact's icon.
# @return [Google::APIClient::Schema::Mirror::V1::Contact]
#   The inserted contact on success, nil otherwise.
def insert_contact(client, contact_id, display_name, image_url)
  mirror = client.discovered_api('mirror', 'v1')
  contact = mirror.contacts.insert.request_schema.new({
    'id' => contact_id,
    'displayName' => display_name,
    'imageUrls' => [image_url]
  })
  result = client.execute(
    :api_method => mirror.contacts.insert,
    :body_object => contact)
  if result.success?
    return result.data
  else
    puts "An error occurred: #{result.data['error']['message']}"
  end
end

Go

Utilizza la libreria client Go.

import (
        "code.google.com/p/google-api-go-client/mirror/v1"
        "fmt"
)

// InsertContact inserts a new contact for the current user.
func InsertContact(g *mirror.Service, contactId string,
        displayName string, iconUrl string) (*mirror.Contact, error) {
        s := &mirror.Contact{
                Id:          contactId,
                DisplayName: displayName,
                ImageUrls:     []string{iconUrl},
        }
        r, err := g.Contacts.Insert(s).Do()
        if err != nil {
                fmt.Printf("An error occurred: %v\n", err)
                return nil, err
        }
        return r, nil
}

HTTP non elaborato

Non utilizza una libreria client.

POST /mirror/v1/contacts HTTP/1.1
Authorization: Bearer auth token
Content-Type: application/json
Content-Length: length

{
  "id": "harold"
  "displayName": "Harold Penguin",
  "imageUrls": ["https://developers.google.com/glass/images/harold.jpg"]
}