Cookbook
Exemple complete, în Python, PHP și JavaScript, pentru operațiile uzuale.
Operație |
Rute |
|---|---|
|
|
|
|
|
|
|
|
|
Rulare
Limbaj |
Cerințe |
Comandă |
|---|---|---|
Python |
3.9+, |
|
PHP |
8.1+, |
|
JavaScript |
Node.js 18+ |
|
Exemplele folosesc baza de date demo și certificatul 10999-demo din Autentificare.
Ele se rulează din directorul în care se află fișierul client al limbajului și perechea
10999-demo.crt / 10999-demo.key (conversia în PEM). Datele
din exemple sunt inventate.
Clientul
Fișierul client conține adresa API-ului, căile certificatului și funcțiile api_get și
api_post (apiGet și apiPost în JavaScript), folosite de toate exemplele. Funcțiile întorc
JSON-ul decodat sau, pentru un PDF, conținutul binar. Un răspuns cu cod de eroare ridică
ApiEroare, cu codul HTTP în status și câmpurile cod și details ale răspunsului
(Erori).
Python — client.py
import requests
URL_API = "https://api.icefact.ro:10999/v1/demo"
CERTIFICAT = "10999-demo.crt"
CHEIE = "10999-demo.key"
class ApiEroare(Exception):
def __init__(self, status, cod, details):
super().__init__(" ".join(str(p) for p in (status, cod, details) if p))
self.status = status
self.cod = cod
self.details = details
def _raspuns(r):
if not r.headers.get("Content-Type", "").startswith("application/json"):
if r.ok:
return r.content
# pagină HTML: certificat lipsă sau refuzat, rută sau metodă necunoscută
raise ApiEroare(r.status_code, None, r.reason)
body = r.json()
if not r.ok:
# erorile de parametru ale rutelor search și list nu au details
raise ApiEroare(r.status_code, body.get("cod"), body.get("details", body))
return body
def api_get(ruta, parametri=None):
r = requests.get(f"{URL_API}/{ruta}", params=parametri,
cert=(CERTIFICAT, CHEIE), timeout=120)
return _raspuns(r)
def api_post(ruta, body):
r = requests.post(f"{URL_API}/{ruta}", json=body,
cert=(CERTIFICAT, CHEIE), timeout=120)
return _raspuns(r)
PHP — client.php
<?php
declare(strict_types=1);
const URL_API = 'https://api.icefact.ro:10999/v1/demo';
const CERTIFICAT = '10999-demo.crt';
const CHEIE = '10999-demo.key';
class ApiEroare extends RuntimeException
{
public function __construct(
public readonly int $status,
public readonly ?string $cod,
public readonly mixed $details,
) {
$text = is_string($details) ? $details : json_encode($details, JSON_UNESCAPED_UNICODE);
parent::__construct(trim("$status $cod $text"));
}
}
function api_cerere(string $metoda, string $ruta, array $parametri = [], ?array $body = null): mixed
{
$url = URL_API . '/' . $ruta . ($parametri ? '?' . http_build_query($parametri) : '');
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $metoda,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSLCERT => CERTIFICAT,
CURLOPT_SSLKEY => CHEIE,
CURLOPT_TIMEOUT => 120,
]);
if ($body !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body, JSON_UNESCAPED_UNICODE));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
}
$continut = curl_exec($ch);
if ($continut === false) {
throw new RuntimeException(curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$tip = (string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$ok = $status >= 200 && $status < 300;
if (!str_starts_with($tip, 'application/json')) {
if ($ok) {
return $continut;
}
// pagină HTML: certificat lipsă sau refuzat, rută sau metodă necunoscută
throw new ApiEroare($status, null, "HTTP $status");
}
$raspuns = json_decode($continut, true, 512, JSON_THROW_ON_ERROR);
if (!$ok) {
// erorile de parametru ale rutelor search și list nu au details
throw new ApiEroare($status, $raspuns['cod'] ?? null, $raspuns['details'] ?? $raspuns);
}
return $raspuns;
}
function api_get(string $ruta, array $parametri = []): mixed
{
return api_cerere('GET', $ruta, $parametri);
}
function api_post(string $ruta, array $body): mixed
{
return api_cerere('POST', $ruta, [], $body);
}
JavaScript — client.mjs
import { readFileSync } from "node:fs";
import https from "node:https";
export const URL_API = "https://api.icefact.ro:10999/v1/demo";
const CERTIFICAT = "10999-demo.crt";
const CHEIE = "10999-demo.key";
const agent = new https.Agent({
cert: readFileSync(CERTIFICAT),
key: readFileSync(CHEIE),
});
export class ApiEroare extends Error {
constructor(status, cod, details) {
const text = typeof details === "string" ? details : JSON.stringify(details);
super([status, cod, text].filter(Boolean).join(" "));
this.status = status;
this.cod = cod;
this.details = details;
}
}
function cerere(metoda, ruta, parametri, body) {
const url = new URL(`${URL_API}/${ruta}`);
for (const [nume, valoare] of Object.entries(parametri ?? {})) {
url.searchParams.set(nume, valoare);
}
const headere = body === undefined ? {} : { "Content-Type": "application/json" };
return new Promise((resolve, reject) => {
const cer = https.request(url, { method: metoda, agent, headers: headere }, (raspuns) => {
const bucati = [];
raspuns.on("data", (bucata) => bucati.push(bucata));
raspuns.on("end", () => {
const continut = Buffer.concat(bucati);
const ok = raspuns.statusCode >= 200 && raspuns.statusCode < 300;
const json = (raspuns.headers["content-type"] ?? "").startsWith("application/json");
if (!json) {
// pagină HTML: certificat lipsă sau refuzat, rută sau metodă necunoscută
return ok ? resolve(continut) : reject(new ApiEroare(raspuns.statusCode, null, raspuns.statusMessage));
}
const date = JSON.parse(continut.toString("utf8"));
if (ok) {
resolve(date);
} else {
// erorile de parametru ale rutelor search și list nu au details
reject(new ApiEroare(raspuns.statusCode, date.cod ?? null, date.details ?? date));
}
});
});
cer.setTimeout(120000, () => cer.destroy(new Error("Timp depășit")));
cer.on("error", reject);
cer.end(body === undefined ? undefined : JSON.stringify(body));
});
}
export const apiGet = (ruta, parametri) => cerere("GET", ruta, parametri);
export const apiPost = (ruta, body) => cerere("POST", ruta, undefined, body);