Contacts: insert

Autorisation requise

Insère un nouveau contact. Voir un exemple.

Requête

Requête HTTP

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

Autorisation

Cette requête nécessite une autorisation ayant la portée suivante. En savoir plus sur le processus d'authentification et d'autorisation

Champ d'application
https://www.googleapis.com/auth/glass.timeline

Corps de la requête

Dans le corps de la requête, indiquez une ressource Contacts avec les propriétés suivantes:

Nom de propriété Valeur Description Remarques
Propriétés obligatoires
acceptCommands[].type string Type d'opération auquel cette commande correspond. Valeurs autorisées:
  • TAKE_A_NOTE : partage un élément de la chronologie avec la transcription des paroles prononcées par l'utilisateur grâce à la commande de menu vocal "Créer une note".
  • POST_AN_UPDATE : partage un élément de la chronologie avec la transcription des paroles prononcées par l'utilisateur à l'aide de la commande de menu vocal "Publier une mise à jour".
accessible en écriture
displayName string Nom à afficher pour ce contact. accessible en écriture
id string Identifiant de ce contact. Il est généré par l'application et traité comme un jeton opaque. accessible en écriture
imageUrls[] list Ensemble d'URL d'images à afficher pour un contact. La plupart des contacts n'ont qu'une seule image, mais un contact de "groupe" peut inclure jusqu'à huit URL d'image qui seront redimensionnées et recadrées pour former une mosaïque sur le client. accessible en écriture
Propriétés facultatives
acceptCommands[] list Liste des commandes de menu vocal qu'un contact peut gérer. Les Google Glass affichent jusqu'à trois contacts pour chaque commande du menu vocal. S'il y en a plus, les trois contacts dont le priority est le plus élevé sont affichés pour la commande concernée. accessible en écriture
acceptTypes[] list Liste des types MIME pris en charge par un contact. Le contact sera présenté à l'utilisateur si l'une de ses valeurs "acceptType" correspond à l'un des types de pièces jointes associés à l'élément. Si aucune valeur "acceptTypes" n'est définie, le contact est affiché pour tous les éléments. accessible en écriture
phoneNumber string Numéro de téléphone principal du contact. Il peut s'agir d'un numéro complet, avec l'indicatif de pays et d'un indicatif de zone, ou d'un numéro local. accessible en écriture
priority unsigned integer Priorité du contact pour déterminer l'ordre dans une liste de contacts. Les contacts dont la priorité est plus élevée sont affichés avant ceux dont la priorité est plus faible. accessible en écriture
speakableName string Nom de ce contact, tel qu'il doit être prononcé. Si le nom de ce contact doit être prononcé dans un menu de sélection vocale, ce nom est utilisé comme prononciation attendue. Cette option est utile pour les contacts contenant des caractères imprononçables ou dont l'orthographe n'est pas phonétique. accessible en écriture
type string Type pour ce contact. Ceci est utilisé pour le tri dans les interfaces utilisateur. Valeurs autorisées:
  • INDIVIDUAL : représente une seule personne. Il s'agit de la valeur par défaut.
  • GROUP : représente plusieurs personnes.
accessible en écriture

Réponse

Lorsque cette méthode fonctionne, elle renvoie une ressource Contacts dans le corps de réponse.

Exemples

Remarque : Les langages de programmation compatibles ne figurent pas tous dans les exemples de code présentés pour cette méthode (consultez la page Bibliothèques clientes pour obtenir la liste des langages compatibles).

Java

Elle utilise la bibliothèque cliente 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

Elle utilise la bibliothèque cliente.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

Elle utilise la bibliothèque cliente 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

Elle utilise la bibliothèque cliente 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

Elle utilise la bibliothèque cliente 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

Elle utilise la bibliothèque cliente 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 brut

N'utilise pas de bibliothèque cliente.

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"]
}