Referencias API

API significa "Application Programming Interface". Una API proporciona un conjunto de comandos, funciones y protocolos para facilitar la programación de software. Estas funciones predefinidas simplifican la interacción del programador con el sistema operativo, ya que el hardware (monitor, datos en el disco duro, etc.) no tiene que ser direccionado directamente. En lo que se refiere a Internet, las APIs Web están a la vanguardia y también sirven como interfaz para permitir el uso de funciones existentes de terceros.

Image

https://cont1-virtual1.certisend.com/web/container/api/v1/database/data/ar/georef/street

Autenticación

Ante la imparable evolución de aplicaciones, frameworks, lenguajes y alternativas para facilitarnos las tareas de Desarrollo Web en diferentes ámbitos, hablaremos a continuación sobre el modelo de autenticación para API REST de nuestra infraestructura. Las API REST que nuestro cloud entrega son uno de los mejores recursos actuales para cualquier desarrollador y en esta ocasión, queremos que conozcas mejor las caracterí­sticas y el flujo de este modelo.

En el mundo de las API REST, se deben implementar flujos distintos de los habituales en cuanto a la autenticación de usuarios, ya que su arquitectura nos ofrece otro tipo de recursos que los tradicionales. Por lo general, en las aplicaciones web tradicionales, se utilizan las variables de sesión como soporte para memorizar el usuario. Esto viene a decir que en el momento de autenticar un usuario, el servidor genera las correspondientes variables de sesión y en las siguientes páginas consultadas por ese mismo cliente, es capaz de recordar al usuario.

Sin embargo, en las aplicaciones REST, esto no es posible, ya que una de las limitaciones de este sistema es que no se dispone de variables de sesión. Esto es debido a motivos de escalabilidad, ya que las API REST suelen estar alojadas en un cluster de servidores. La solución habitual para salvar este problema es la autenticación por token.

Flujo de autenticación por usuario y contraseña:
El hecho de usar un token como mecanismo involucrado en la autenticación no produce efectos visibles para los usuarios, ya que estos no tienen que lidiar con el directamente. Dicho de otra manera, todas las diferencias en el flujo son transparentes para el usuario.

Nuestro API Cloud Center trabaja de forma estandarizada y por defecto con autenticación de token basado en parámetros querys:

Token de Suscripción (token-susc): Este token permite en cada llamado a la api identificar la suscripción del usuario.
Token de API (token-api): Este token permite identificar la key de la API que se requiere consumir.

Otros Mecanismos de Seguridad:
En caso que el usuario asaí lo requiera pueda proteger sus tokens y keys utilizando diferentes mecanismos de seguridad como:
- Authentication by Header
- API EndPoint to Generate Tokens Dynamics.
- Oauth2

Parámetros de Seguridad
  • token-susc

    Mediante el parámetro token-susc el sistema debera recibir la key seteada a su suscripción y que se encuentra disponible en su Panel Comercial.
    Ejemplo: "token-susc": "20190d614196076fb924df8d92c5as"

  • token-api

    Mediante el parámetro token-api el sistema debera recibir la key seteada a la API que esta queriendo consumir. Dicha API puede ser solicitada desde su Panel Comercial.
    Ejemplo: "token-api": "9f9f0fe087e970b8c21c45e1cd95af"

Errores de Autenticación:
200 - OK OK.
401 - Security Security tokens not found.
401 - Security Security tokens not defined.
401 - Security Security tokens error.
409 - Unauthorized Suscription stoped.
409 - Unauthorized Api offline or discontinued.
429 - Limits Limit exceeded.

Parámetros de Entrada

Mediante el metodo de llamado get la API Street_Advanced_Arg_Database (Advanced street information (Argentina)) puede recibir los siguientes parámetros de entrada:

Parámetros de Entrada

  • street

    Tipo: string
    Requerido: true
    Formato: query


  • category

    Tipo: string
    Requerido: false
    Formato: query


  • province

    Tipo: string
    Requerido: false
    Formato: query


  • department

    Tipo: string
    Requerido: false
    Formato: query


  • census_location

    Tipo: string
    Requerido: false
    Formato: query


curl -X GET "https://cont1-virtual1.certisend.com/web/container/api/v1/database/data/ar/georef/street?token-susc=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&token-api=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&street=VALUE_OF_STREET&category=VALUE_OF_CATEGORY&province=VALUE_OF_PROVINCE&department=VALUE_OF_DEPARTMENT&census_location=VALUE_OF_CENSUS_LOCATION&internalid=YOUR_INTERNAL_ID" -H "accept: application/json"
										

import requests
r = requests.get('https://cont1-virtual1.certisend.com/web/container/api/v1/database/data/ar/georef/street?token-susc=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&token-api=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&street=VALUE_OF_STREET&category=VALUE_OF_CATEGORY&province=VALUE_OF_PROVINCE&department=VALUE_OF_DEPARTMENT&census_location=VALUE_OF_CENSUS_LOCATION&internalid=YOUR_INTERNAL_ID')
r.json()
										

require 'net/http'
require 'json'

url = 'https://cont1-virtual1.certisend.com/web/container/api/v1/database/data/ar/georef/street?token-susc=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&token-api=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&street=VALUE_OF_STREET&category=VALUE_OF_CATEGORY&province=VALUE_OF_PROVINCE&department=VALUE_OF_DEPARTMENT&census_location=VALUE_OF_CENSUS_LOCATION&internalid=YOUR_INTERNAL_ID'
uri = URI(url)
response = Net::HTTP.get(uri)
JSON.parse(response)
										

$json = file_get_contents('https://cont1-virtual1.certisend.com/web/container/api/v1/database/data/ar/georef/street?token-susc=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&token-api=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&street=VALUE_OF_STREET&category=VALUE_OF_CATEGORY&province=VALUE_OF_PROVINCE&department=VALUE_OF_DEPARTMENT&census_location=VALUE_OF_CENSUS_LOCATION&internalid=YOUR_INTERNAL_ID');
echo $json;
$obj = json_decode($json);
										

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

public class JsonReader {

	private static String readAll(Reader rd) throws IOException {
		StringBuilder sb = new StringBuilder();
		int cp;
		while ((cp = rd.read()) != -1) {
			sb.append((char) cp);
		}
		return sb.toString();
	}

	public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
		InputStream is = new URL(url).openStream();
		try {
			BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
			String jsonText = readAll(rd);
			JSONObject json = new JSONObject(jsonText);
			return json;
		} finally {
			is.close();
		}
	}

	public static void main(String[] args) throws IOException, JSONException {
		JSONObject json = readJsonFromUrl("https://cont1-virtual1.certisend.com/web/container/api/v1/database/data/ar/georef/street?token-susc=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&token-api=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&street=VALUE_OF_STREET&category=VALUE_OF_CATEGORY&province=VALUE_OF_PROVINCE&department=VALUE_OF_DEPARTMENT&census_location=VALUE_OF_CENSUS_LOCATION&internalid=YOUR_INTERNAL_ID");
		System.out.println(json.toString());
		System.out.println(json.get("id"));
	}
}
										

Private Function GetAPIDATA() As String
	Dim xmlHttp As Object
	Dim strTokenSusc as String
	Dim strTokenAPI as String
	Dim strUrl as String

	strTokenSusc = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
	strTokenAPI = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

	strUrl = "https://cont1-virtual1.certisend.com/web/container/api/v1/database/data/ar/georef/street?token-susc=" & strTokenSusc & "&token-api=" & strTokenAPI & "&street=VALUE_OF_STREET&category=VALUE_OF_CATEGORY&province=VALUE_OF_PROVINCE&department=VALUE_OF_DEPARTMENT&census_location=VALUE_OF_CENSUS_LOCATION&internalid=YOUR_INTERNAL_ID"


	Set xmlHttp = CreateObject("MSXML2.XmlHttp")
	xmlHttp.Open "GET", sURL, False
	xmlHttp.send
	GetAPIDATA = xmlHttp.responseText
	Set xmlHttp = Nothing
End Function
										

<%
	dim url
	url = "https://cont1-virtual1.certisend.com/web/container/api/v1/database/data/ar/georef/street?token-susc=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&token-api=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&street=VALUE_OF_STREET&category=VALUE_OF_CATEGORY&province=VALUE_OF_PROVINCE&department=VALUE_OF_DEPARTMENT&census_location=VALUE_OF_CENSUS_LOCATION&internalid=YOUR_INTERNAL_ID"
	Set HttpReq = Server.CreateObject("MSXML2.ServerXMLHTTP")
	HttpReq.open "GET", url, false
	HttpReq.setRequestHeader "Content-Type", "application/json"
	HttpReq.Send()
%>
										

using (var httpClient = new System.Net.Http.HttpClient())
{
	var json = await httpClient.GetStringAsync("https://cont1-virtual1.certisend.com/web/container/api/v1/database/data/ar/georef/street?token-susc=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&token-api=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&street=VALUE_OF_STREET&category=VALUE_OF_CATEGORY&province=VALUE_OF_PROVINCE&department=VALUE_OF_DEPARTMENT&census_location=VALUE_OF_CENSUS_LOCATION&internalid=YOUR_INTERNAL_ID");
}
										

var https = require('https');

var options = {
	host: 'https://cont1-virtual1.certisend.com/web/container/api/v1/',
	path: 'database/data/ar/georef/street?token-susc=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&token-api=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&street=VALUE_OF_STREET&category=VALUE_OF_CATEGORY&province=VALUE_OF_PROVINCE&department=VALUE_OF_DEPARTMENT&census_location=VALUE_OF_CENSUS_LOCATION&internalid=YOUR_INTERNAL_ID',
	headers: {
		'Accept': 'application/json'
	}
};
https.get(options, function (res) {
	var json = '';

	res.on('data', function (chunk) {
		json += chunk;
	});

	res.on('end', function () {
		if (res.statusCode === 200) {
			try {
				var data = JSON.parse(json);
				// data is available here:
				console.log(json);
			} catch (e) {
				console.log('Error parsing JSON!');
			}
		} else {
			console.log('Status:', res.statusCode);
		}
	});
}).on('error', function (err) {
	console.log('Error:', err);
});
										

package main

import (
		"fmt"
		"net/http"
		"io/ioutil"
		"os"
	)

func main() {
	response, err := http.Get("https://cont1-virtual1.certisend.com/web/container/api/v1/database/data/ar/georef/street?token-susc=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&token-api=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&street=VALUE_OF_STREET&category=VALUE_OF_CATEGORY&province=VALUE_OF_PROVINCE&department=VALUE_OF_DEPARTMENT&census_location=VALUE_OF_CENSUS_LOCATION&internalid=YOUR_INTERNAL_ID")
	if err != nil {
		fmt.Printf("%s", err)
		os.Exit(1)
	} else {
		defer response.Body.Close()
		contents, err := ioutil.ReadAll(response.Body)
		if err != nil {
			fmt.Printf("%s", err)
			os.Exit(1)
			}
			fmt.Printf("%s\n", string(contents))
	}
}
										

Parámetros de Salida

Una vez consumida la API y siempre y cuando la respuesta de la misma y el contro de autenticación retorne un 200-OK, la misma arrojara los siguientes campos de salida en formato JSON:

Campo Tipo Longitud Descripción
state string Validation results -> 0:(street not found / missing parameter), 1:(data found / validated).
desc string Description of the parameter state.
data string Result of the data.
streets string Streets found.
altura string Length of the street found.
fin string Last numbers of the street.
derecha(1) string Last number of the right side.
izquierda(1) string Last number of the left side.
start string First numbers of the street.
derecha(2) string First number of the right side.
izquierda(2) string First number of the left side.
categoria string Street type.
departamento string Deparment that contains the street.
id(1) string Deparment ID.
nombre(1) string Department name.
id(2) string Street ID.
localidad_censal string Census locality that contains the street found.
id(3) string Census locality ID.
nombre(2) string Name of the census locality.
nombre(3) string Name of the street found.
nomenclatura string Street complete definition compose for its name, department and province.
provincia string Province that contains the street.
id(4) string Province ID.
nombre(4) string Name of the province.
quantity string Quantity of results found.
parameters string Parameters used.
categoria(2) string Type of street inserted on the query.
departamento(2) string Department inserted on the query.
localidad_censal(2) string Census locality inserted on the query.
nombre(5) string Name of the street consulted.
provincia(2) string Province inserted on the query.
amount string Total account of results found.
internalid string Internal ID.
Otros Códigos HTTP
200 - OK Respuesta estandar para peticiones correctas.
400 - Bad Request El servidor no procesar la solicitud, porque no puede, o no debe, debido a algo que es percibido como un error del cliente (ej: solicitud malformada, sintaxis errónea, etc). La solicitud contiene sintaxis errónea y no debería repetirse.
401 - Unauthorized Similar al 403 Forbidden, pero específicamente para su uso cuando la autentificación es posible pero ha fallado o aún no ha sido provista.
404 - Not Found Una petición fue hecha a una URI utilizando un metodo de solicitud no soportado por dicha URI; por ejemplo, cuando se utiliza GET en un formulario que requiere que los datos sean presentados vía POST, o utilizando PUT en un recurso de solo lectura.
409 - Conflict Indica que la solicitud no pudo ser procesada debido a un conflicto con el estado actual del recurso que esta identifica.
429 - Too Many Requests Hay muchas conexiones desde esta dirección de internet.
500, 502, 503, 504 - Server Errors El servidor falló al completar una solicitud aparentemente válida.