Saltar a contenido

Client-key

El client-key es un token especial que es necesario para la mayoría de las peticiones del API de PhotoILike. La idea es que cada usuario final disponga de un client-key único.

El recurso client-key requiere de varias peticiones que se detallan a continuación.

Creación de client-key

Warning

PhotoILike no almacena los tokens de los client-keys. Es importante que se almacenen de manera segura porque PhotoILike no puede obtener el token de un client-key que se generó anteriormente.

Petición

POST https://api.photoilike.com/v2.0/client-key

Cabeceras

Campos

Clave Valor
Authorization string
Requerido
Token de sesión precedido por la palabra Bearer.

Cuerpo de la solicitud

El cuerpo de la solicitud contiene datos con la siguiente estructura:

Representación JSON

{
    "send": bool,
    "clients": [
        {"name": string, "email": string},
        ...
    ]
}

Campos

Parámetro Información
send bool
Opcional.
Si el campo es cierto se enviará al correo de la cuenta registrada de PhotoILike todos los client-keys generados.
clients array
Requerido.
Array de pares nombre-email que identifican al cliente para el que se va a crear el client-key (la capacidad máxima del array en una petición es de 20).
clients[item].name string
Requerido.
Nombre del cliente al que se le quiere generar el client-key.
clients[item].email array
Requerido.
Cuenta de correo del cliente al que se le quiere generar el client-key.

Respuesta de la solicitud

En caso de éxito, el código de estado HTTP en el encabezado de la respuesta es 200 OK y el cuerpo de la respuesta contiene un array con los client-keys generados.

Representación

[
    {
        "id": string,
        "activated": bool,
        "email": string,
        "name": string,
        "secret" string
    },
    ...
]

Campos

Parámetro Información
id string
Identificador con el que PhotoILike almacena la información relativa al client-key.
activated bool
Indica si el client-key está activado para usarse o no.
name string
Nombre del cliente que se usó en la petición.
email string
Email del cliente que se usó en la petición.
secret string
Token del client-key. Esta información ha de guardarse en un lugar seguro porque PhotoILike no almacena el token generado haciendo imposible recuperarlo ni restaurarlo.

Ejemplo de petición

curl --request POST \
--header "Content-Type: application/json" \
--header "Authorization: Bearer {YOUR.SESSION.TOKEN}" \
--data '{"send": "True", "clients": [{"name": "client1", "email": "client1@example.org"}, {"name": "client2", "email": "client2@example.org"}]}' \
https://api.photoilike.com/v2.0/client-key 
import requests
header = {
    # Add your token session (1)
    'Authorization': 'Bearer YOUR.SESSION.TOKEN'
}
clients = [
    # Set the right values for your clients (2)
    {'name': 'client1', 'email': 'client1@example.org'},
    {'name': 'client2', 'email': 'client2@example.org'}
]
payload = {
    # If send is true an email will be sent to your email account with all the created client-keys
    'send': True,
    'clients': clients
}
endpoint = 'https://api.photoilike.com/v2.0/client-key'
# Make the request
r = requests.post(endpoint, headers=header, json=payload)
# Response in json format
response = r.json()
  1. Asegúrese de sustituir YOUR.SESSION.TOKEN por un token de sesión válido
  2. Establezca el valor name y email adecuados para sus clientes
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import org.json.JSONArray;
import org.json.JSONObject;

public class ClientKey {

    public static void main(String []args) throws Exception {

        // add your session token (1)
        String bearerToken = String.format("Bearer %s", "YOUR.SESSION.TOKEN");

        // set the right values for your clients (2)
        JSONObject client1 = new JSONObject();
        client1.put("name", "client1");
        client1.put("email", "client1@example.org");

        JSONObject client2 = new JSONObject();
        client2.put("name", "client1");
        client2.put("email", "client1@example.org");

        JSONArray clients = new JSONArray();
        clients.put(client1);
        clients.put(client2);

        JSONObject payload = new JSONObject();
        // if send is true an email will be sent to your email account with all the created client-keys
        payload.put("send", true);
        payload.put("clients", clients);


        String endpoint = "https://api.photoilike.com/v2.0/client-key";

        // build the request
        HttpURLConnection connection = (HttpURLConnection) new URL(endpoint).openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", bearerToken);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        OutputStream os = connection.getOutputStream();
        byte[] input = payload.toString().getBytes(StandardCharsets.UTF_8);
        os.write(input, 0, input.length);

        // make the request
        BufferedReader br = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)
        );
        StringBuilder response = new StringBuilder();

        for (String responseLine = null; (responseLine = br.readLine()) != null; response.append(responseLine.trim()))
            ;

        // Response in json format
        JSONArray json = new JSONArray(response.toString());
    }
}
  1. Asegúrese de sustituir YOUR.SESSION.TOKEN por un token de sesión válido
  2. Establezca el valor name y email adecuados para sus clientes
<?php

  // Add your token session (1)
  $headers = array(
    'Content-Type:application/json',
    'Authorization: Bearer YOUR.SESSION.TOKEN'
  );

  // Set the right values for your clients (2)
  $clients = array(
    array(
      'name' => 'client1',
      'email' => 'client1@example.org'
    ),
    array(
      'name' => 'client2',
      'email' => 'client2@example.org'
    )
  );

  // If send is true and email will be sent to your email account with all the created client-keys
  $payload = json_encode(array(
    'send' => true,
    'clients' => $clients
  ));

  $endpoint = "https://api.photoilike.com/v2.0/client-key";

  $ch = curl_init($endpoint);
  curl_setopt($ch,  CURLOPT_POSTFIELDS, $payload);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  // Make the request
  $result = curl_exec($ch);

  curl_close($ch);

  // Response in json format    
  $response = json_decode($result);
 ?>
  1. Asegúrese de sustituir YOUR.SESSION.TOKEN por un token de sesión válido
  2. Establezca el valor name y email adecuados para sus clientes

Desactivación de client-key

Info

El estado de un client-key solo puede transicionar de activado a desactivado. Esto supone que no se puede activar un client-key que haya sido desactivado.

Petición

PUT https://api.photoilike.com/v2.0/client-key

Cabeceras

Campos

Clave Valor
Authorization string
Requerido
Token de sesión precedido por la palabra Bearer.

Cuerpo de la solicitud

El cuerpo de la solicitud contiene datos con la siguiente estructura:

Representación JSON

{
    "id": string
}

Campos

Parámetro Información
id string
Requerido
Identificador con el que PhotoILike almacena la información relativa al client-key.

Respuesta de la solicitud

En caso de éxito, el código de estado HTTP en el encabezado de la respuesta es 200 OK y el cuerpo de la respuesta contiene un objeto con el client-key modificado.

Representación JSON

{
    "id": string,
    "activated": bool,
    "email": string,
    "name": string,
    "timestamp": timestamp
}

Campos

Parámetro Información
id string
Identificador con el que PhotoILike almacena la información relativa al client-key.
activated bool
Indica si el client-key está activado para usarse o no.
name string
Nombre del cliente que se usó en la petición.
email string
Email del cliente que se usó en la petición.
timestamp timestamp
Instante de tiempo en el que el client-key fue generado.

Ejemplo de petición

curl --request PUT \
--header "Content-Type: application/json" \
--header "Authorization: Bearer {YOUR.SESSION.TOKEN}" \
--data '{"id": "{CLIENT_KEY_ID}"}' \
https://api.photoilike.com/v2.0/client-key 
import requests

header = {
    # Add your token session (1)
    'Authorization': 'Bearer YOUR.SESSION.TOKEN'
}

payload = {
    # Add the id of the client-key to desactivated (2)
    'id': "CLIENT_KEY_ID"
}

endpoint = 'https://api.photoilike.com/v2.0/client-key'

# Make the request
r = requests.put(endpoint, headers=header, json=payload)

# Response in json format
response = r.json()
  1. Asegúrese de sustituir YOUR.SESSION.TOKEN por un token de sesión válido
  2. Asegúrese de cambiar CLIENT_KEY_ID por un identificador de client-key válido
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import org.json.JSONArray;
import org.json.JSONObject;

public class ClientKey {
    public static void main(String []args) throws Exception {
        // add your session token (1)
        String bearerToken = String.format("Bearer %s", "YOUR.SESSION.TOKEN");


        JSONObject payload = new JSONObject();
        // add the id of the client-key to deactivated (2)
        payload.put("id", "CLIENT_KEY_ID");



        String endpoint = "https://api.photoilike.com/v2.0/client-key";

        // build the request
        HttpURLConnection connection = (HttpURLConnection) new URL(endpoint).openConnection();
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Authorization", bearerToken);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        OutputStream os = connection.getOutputStream();
        byte[] input = payload.toString().getBytes(StandardCharsets.UTF_8);
        os.write(input, 0, input.length);

        // make the request
        BufferedReader br = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)
        );
        StringBuilder response = new StringBuilder();

        for (String responseLine = null; (responseLine = br.readLine()) != null; response.append(responseLine.trim()))
            ;

        // Response in json format
        JSONObject json = new JSONObject(response.toString());
    }

}
  1. Asegúrese de sustituir YOUR.SESSION.TOKEN por un token de sesión válido
  2. Asegúrese de cambiar CLIENT_KEY_ID por un identificador de client-key válido
<?php

  // Add your token session (1)
  $headers = array(
    'Content-Type:application/json',
    'Authorization: Bearer YOUR.SESSION.TOKEN'
  );

  // Add the id of the client-key to desactivated (2)
  $payload = json_encode(array(
    'id' => 'CLIENT_KEY_ID'
  ));

  $endpoint = "https://api.photoilike.com/v2.0/client-key";

  $ch = curl_init($endpoint);
  curl_setopt($ch,  CURLOPT_POSTFIELDS, $payload);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");

  // Make the request
  $result = curl_exec($ch);

  curl_close($ch);

  // Response in json format
  $response = json_decode($result);
 ?>
  1. Asegúrese de sustituir YOUR.SESSION.TOKEN por un token de sesión válido
  2. Asegúrese de cambiar CLIENT_KEY_ID por un identificador de client-key válido

Obtención de client-keys

Petición

GET https://api.photoilike.com/v2.0/client-key

Cabeceras

Campos

Clave Valor
Authorization string
Requerido
Token de sesión precedido por la palabra Bearer.

Parámetros de consulta

Campos

Clave Valor
page int
Opcional
Número de la página de la que se quiere obtener los client-keys. Si no se especifica el valor que se usa por defecto es 0.

Respuesta de la solicitud

En caso de éxito, el código de estado HTTP en el encabezado de la respuesta es 200 OK y el cuerpo de la respuesta contiene un array con los client-keys.

Representación

[
    {
        "id": string,
        "activated": bool,
        "name": string,
        "email": string,
        "timestamp": timestamp,
        "apiKeyPrefix": string,
    },
    ...
]

Campos

Parámetro Información
id string
Identificador con el que PhotoILike almacena la información relativa al client-key.
activated bool
Indica si el client-key está activado para usarse o no.
name string
Nombre del cliente que se usó en la petición.
email string
Email del cliente que se usó en la petición.
timestamp timestamp
Instante de tiempo en el que el client-key fue generado.
apiKeyPrefix string
Los primeros caracteres del token del client-key.

Esta petición también emplea las cabeceras para añadir más información en la respuesta.

Clave Valor
x-total-count string
Número total de client-keys.
link string
Contiene un listado de elementos <link> separados por coma de la siguiente forma:
<uri_referencia>; rel="valor", <uri_referencia>; rel="valor"
Los posibles valores en el campo rel son: next, prev, first y last.

Ejemplo de petición

curl --request GET \
--header "Content-Type: application/json" \
--header "Authorization: Bearer {YOUR.SESSION.TOKEN}" \
https://api.photoilike.com/v2.0/client-key?page={NUM_PAGE}
import requests

header = {
    # Add your token session (1)
    'Authorization': 'Bearer YOUR.SESSION.TOKEN'
}

params = {
    # Add the num page to retrieve it (2)
    "page": 1
}

endpoint = 'https://api.photoilike.com/v2.0/client-key'

# Make the request
r = requests.get(endpoint, headers=header, params=params)

# Response in json format
response = r.json()
  1. Asegúrese de sustituir YOUR.SESSION.TOKEN por un token de sesión válido
  2. Establezca en page el número de página que desee obtener
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import org.json.JSONArray;
import org.json.JSONObject;

public class ClientKey {

    public static void main(String []args) throws Exception {
        // add your session token (1)
        String bearerToken = String.format("Bearer %s", "YOUR.SESSION.TOKEN");

        // add the num page to retrieve it (2)
        int page = 1;

        String endpoint = "https://api.photoilike.com/v2.0/client-key?page=" + page;

        // build the request
        HttpURLConnection connection = (HttpURLConnection) new URL(endpoint).openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", bearerToken);

        // make the request
        BufferedReader br = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)
        );
        StringBuilder response = new StringBuilder();

        for (String responseLine = null; (responseLine = br.readLine()) != null; response.append(responseLine.trim()))
            ;

        // Response in json format
        JSONArray json = new JSONArray(response.toString());
    }

}
  1. Asegúrese de sustituir YOUR.SESSION.TOKEN por un token de sesión válido
  2. Establezca en page el número de página que desee obtener
<?php

  // Add your token session (1)
  $headers = array(
    'Content-Type:application/json',
    'Authorization: Bearer YOUR.SESSION.TOKEN'
  );


  $endpoint = "https://api.photoilike.com/v2.0/client-key";
  // Add the num page to retrieve it (2)
  $endpoint = $endpoint . "?page=1";

  $ch = curl_init($endpoint);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  // Make the request
  $result = curl_exec($ch);

  curl_close($ch);

  // Response in json format
  $response = json_decode($result);
 ?>
  1. Asegúrese de sustituir YOUR.SESSION.TOKEN por un token de sesión válido
  2. Establezca en page el número de página que desee obtener