Exemple Hello World
Exemple Hello World
Créons un endpoint API simple associé à un utilisateur.
1. Créer l’utilisateur et la fonction
Dans votre base de données (my_database) :
-- 1. Créer un utilisateur qui se connectera à l'API
CREATE ROLE demo_user WITH LOGIN PASSWORD 'user_password';
GRANT USAGE ON SCHEMA api TO demo_user;
-- 2. Créer la fonction Hello World
-- Entrée : jsonb vide, Sortie : json
CREATE OR REPLACE FUNCTION api.hello_world(payload jsonb)
RETURNS json
LANGUAGE sql
AS $$
SELECT '"Hello World"'::json;
$$;
-- 3. Accorder les permissions à l'utilisateur
GRANT EXECUTE ON FUNCTION api.hello_world(jsonb) TO demo_user;Choisir votre méthode d’authentification
PgArachne propose deux approches pour cet exemple :
- Option A — Flux de jeton JWT : obtenez un jeton via
get_jwtet utilisez-le comme en-têteBearer. Nécessite unGRANT demo_user TO pgarachnesupplémentaire. - Option B — Identifiants directs : envoyez directement le nom d’utilisateur et le mot de passe via HTTP Basic Auth. Aucun
GRANTsupplémentaire requis.
Option A — Flux de jeton JWT
A1. Autoriser PgArachne à basculer vers demo_user
-- Permettre à PgArachne (utilisateur système) de passer à demo_user
GRANT demo_user TO pgarachne;A2. Obtenir un jeton JWT
Utilisez la méthode JSON-RPC get_jwt pour obtenir un token JWT :
curl -X POST http://localhost:8080/db/my_database/jsonrpc \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"get_jwt","params":{"login":"demo_user","password":"user_password"},"id":1}'Réponse :
{"jsonrpc":"2.0","result":{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."},"id":1}A3. Appeler la fonction avec le jeton
export TOKEN="VOTRE_TOKEN_JWT_ICI"
curl -X POST http://localhost:8080/db/my_database/jsonrpc \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "method": "api.hello_world", "params": {}, "id": 1}'Réponse :
{"jsonrpc": "2.0", "result": "Hello World", "id": 1}Option B — Identifiants directs
Aucun GRANT … TO pgarachne n’est nécessaire. Envoyez directement les identifiants PostgreSQL
via HTTP Basic Auth :
curl -u demo_user:user_password \
-X POST http://localhost:8080/db/my_database/jsonrpc \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "method": "api.hello_world", "params": {}, "id": 1}'Réponse :
{"jsonrpc": "2.0", "result": "Hello World", "id": 1}Pour en savoir plus sur les méthodes d’authentification disponibles, consultez la page Sécurité & Authentification — Informations d’identification directes.