Cours > Module > Chapitre

Lab : Création d’une API GraphQL Serverless avec AWS AppSync

Objectif

Ce lab vous guide dans la création d’une API GraphQL Serverless avec AWS AppSync et DynamoDB. Vous apprendrez à :

Créer un backend GraphQL avec AWS AppSync.
Configurer DynamoDB comme source de données.
Tester les requêtes et mutations GraphQL.
Créer une interface Web pour interagir avec l’API (S3 Static Website).

1. Architecture du Lab

  • Amazon DynamoDB pour stocker les utilisateurs.
  • AWS AppSync pour exposer une API GraphQL.

Amazon S3 pour héberger une interface web statique pour tester l’API.

2. Création du Backend avec AWS AppSync

1. Créer une Table DynamoDB

  1. AWS Console > DynamoDB > Créer une table.
  2. Nom : Users.
  3. Clé primaire : user_id (Type : String).
  4. Mode de capacité : On-Demand.
  5. Créer la table.

2. Créer une API AWS AppSync

  1. AWS Console > AppSync > Create API.
  2. Choisissez “Build from scratch”.
  3. Nom : UserAPI.
  4. Authentification : Amazon Cognito (ou API Key pour simplifier).
  5. Créer l’API.

3. Définir le Schéma GraphQL

Dans AppSync > Schema, remplacez le contenu par :

				
					mutation {
    addUser(name: "Alice", email: "alice@example.com") {
        user_id
        name
        email
    }
}


				
			

Exécutez la requête pour récupérer un utilisateur :

				
					query {
    getUser(user_id: "12345") {
        name
        email
    }
}

				
			

Exécutez la requête pour lister tous les utilisateurs :

				
					query {
    listUsers {
        user_id
        name
        email
    }
}

				
			

4. Création d’une Interface Web sur S3

1. Créer un Bucket S3

  1. AWS Console > S3 > Create Bucket.
  2. Nom : user-api-frontend.
  3. Désactiver le “Block all public access”.
  4. Activer “Static website hosting”.

2. Ajouter le Code HTML

Créez un fichier index.html avec :

				
					<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test API GraphQL</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }
        input, button { margin: 5px; padding: 10px; }
        #result { margin-top: 20px; }
    </style>
</head>
<body data-rsssl=1>
    <h2>Ajouter un Utilisateur</h2>
    <input type="text" id="name" placeholder="Nom">
    <input type="email" id="email" placeholder="Email">
    <button onclick="addUser()">Ajouter</button>

    <h2>Récupérer un Utilisateur</h2>
    <input type="text" id="user_id" placeholder="User ID">
    <button onclick="getUser()">Rechercher</button>

    <div id="result"></div>

    <script>
        const API_URL = "https://your-appsync-api/graphql";  // Remplacez avec l'URL de votre API AppSync
        const API_KEY = "your-api-key";  // Si vous utilisez API Key

        async function addUser() {
            const name = document.getElementById("name").value;
            const email = document.getElementById("email").value;

            const response = await fetch(API_URL, {
                method: "POST",
                headers: { "Content-Type": "application/json", "x-api-key": API_KEY },
                body: JSON.stringify({ query: `mutation { addUser(name: "${name}", email: "${email}") { user_id } }` })
            });

            const data = await response.json();
            document.getElementById("result").innerHTML = "Utilisateur ajouté: " + data.data.addUser.user_id;
        }

        async function getUser() {
            const user_id = document.getElementById("user_id").value;

            const response = await fetch(API_URL, {
                method: "POST",
                headers: { "Content-Type": "application/json", "x-api-key": API_KEY },
                body: JSON.stringify({ query: `query { getUser(user_id: "${user_id}") { name email } }` })
            });

            const data = await response.json();
            document.getElementById("result").innerHTML = data.data.getUser
                ? `Nom: ${data.data.getUser.name}, Email: ${data.data.getUser.email}`
                : "Utilisateur non trouvé";
        }
    </script>
</body>
</html>

				
			
  1. Téléversez index.html sur S3.

Testez votre interface en visitant l’URL du site statique S3. 🚀

Conclusion

✅ API GraphQL Serverless avec AWS AppSync.
✅ DynamoDB comme backend NoSQL.
✅ Interface web statique sur S3 pour tester l’API
. 🚀

×

Panier