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;

-- 4. Permettre à PgArachne (utilisateur système) de passer à demo_user
GRANT demo_user TO pgarachne;

2. Connexion via l’API

Utilisez la méthode JSON-RPC login pour obtenir un token JWT :

curl -X POST http://localhost:8080/api/my_database \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"login","params":{"login":"demo_user","password":"user_password"},"id":1}'

Réponse :

{"jsonrpc":"2.0","result":{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."},"id":1}

3. Appeler la fonction

Utilisez le token pour appeler la fonction hello_world :

export TOKEN="VOTRE_TOKEN_JWT_ICI"

curl -X POST http://localhost:8080/api/my_database \
  -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}