Interface

 

Partie 1 – Serveur

  • réaliser des URI permettant d’exécuter vos triggers.
  • réaliser des URI permettant d’exécuter vos  procédures stockées.
  • réaliser des URI permettant de visualiser ces changements (affichage des membres, recherche d’un membre etc).
  • déployer l’API.

 

<?php 
require 'vendor/autoload.php';
use \Psr\Http\Message\{ServerRequestInterface as Request,ResponseInterface as Response};
 
$app = new \Slim\App;

//GET /gateau/:id
$app->get('/gateau/{id}', function(Request $request, Response $response){
	$id = $request->getAttribute('id');
       return $id;
});
//POST /gateau?id=x&nom=z
$app->post('/gateau', function(Request $request, Response $response){
	$id = $request->getQueryParam('id');	
	$nom = $request->getQueryParam('nom');	
        //fonction d'insertion
	return setGateau($id, $nom);
});
//GET /gateaux
$app->get('/gateaux', function(Request $request, Response $response){
	return getGateaux();
});


function connexion()
{
    /*IBM Cloud
     * $vcap_services = json_decode($_ENV['VCAP_SERVICES'], true);
     * $uri = $vcap_services['compose-for-mysql'][0]['credentials']['uri'];
     * $db_creds = parse_url($uri);
     * $dbname = "patisserie";
     * $dsn = "mysql:host=" . $db_creds['host'] . ";port=" . $db_creds['port'] . ";dbname=" . $dbname;
     * return $dbh = new PDO($dsn, $db_creds['user'], $db_creds['pass'],array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
     * */
    //autre
    return $dbh = new PDO("mysql:host=localhost;dbname=patisserie", 'root', '', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
}
function setGateau($id, $nom)
{
    $sql = "INSERT INTO gateau VALUES(:id, :nom))";
    try {
        $dbh = connexion();
 
        $req = $dbh->prepare($sql);
        $res = $req->execute(array(
            ':id' => $id,
            ':nom' => $nom,
        ));
        return $res;
    } catch (PDOException $e) {
        return '{"error":' . $e->getMessage() . '}}';
    }
}
function getGateaux()
{
	$sql = "SELECT * FROM gateau";
	try{
		$dbh=connexion();
		$statement = $dbh->prepare($sql);
		$statement->execute();
		 $result = $statement->fetchAll(PDO::FETCH_CLASS); 
                 return json_encode($result, JSON_PRETTY_PRINT);
	} catch(PDOException $e){
		return '{"error":'.$e->getMessage().'}}';
	}
}
$app->run();

 

from flask import Flask
from flask import request
from flask import jsonify
from flaskext.mysql import MySQL
import json

app = Flask(__name__)

mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'patisserie'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

@app.route("/")
def hello():
    return "Hello World!"

@app.route("/bonjour")
def bonjour():
    return "Bonjour"

@app.route('/success/<name>')
def success(name):
   return 'welcome %s' % name

@app.route('/gateau') 
def data(): 
	id = request.args.get('id')
	nom = request.args.get('nom')
	conn = mysql.connect()
	cursor = conn.cursor()
	cursor.execute('insert into gateau values('+id+',"'+nom+'")')
	data = cursor.fetchall()
	if len(data) is 0:
		return json.dumps({'message':'gateau created successfully !'})
	else:
		return json.dumps({'error':str(data[0])})
	conn.close()

@app.route('/gateaux') 
def data2(): 
	conn = mysql.connect()
	cursor = conn.cursor()
	cursor.execute('select * from gateau')
	data = cursor.fetchall()
	if len(data) != 0:
		return jsonify(data)
	else:
		return json.dumps({'error':str(data[0])})
	conn.close()

if __name__ == '__main__':
    app.run(debug=True)

Partie 2 – client

  • Réaliser les interfaces HTML nécessaires pour les routes. On pourra utiliser le plugin Bootstrap Table.
  • Déployer les interfaces.

client.html

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="client de l'API gateau">
    <meta name="author" content="Luc Frébourg">
    <title>API Gateau</title>


    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
            integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
            crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
            integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
            crossorigin="anonymous"></script>

    <!--tables-->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.12.1/bootstrap-table.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.12.1/bootstrap-table.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.12.1/locale/bootstrap-table-zh-CN.min.js"></script>


</head>

<body class="mesforms">
<div class="page container">


    <h3>Insertion en POST</h3>
    <div class="form-group">
        <label for="id" class=" col-md-8 col-lg-6 col-form-label">Identifiant du gâteau</label>
        <div class="col-md-8 col-lg-6">
            <input class="form-control" required="required" type="text" value="" id="id">
        </div>
        <label for="nom" class=" col-md-8 col-lg-6 col-form-label">Nom du gâteau</label>
        <div class=" col-md-8 col-lg-6">
            <input class="form-control" required="required" type="text" value="" id="nom">
        </div>
    </div>
    <div class="col-md-8 col-lg-6">
        <button class="btn btn-primary" id="btn-insert-gateau">Valider</button>
    </div>
    <br><br>


    <h3>Affichage en GET</h3>
    <div class="form-group form-group-nom ">
        <label for="idx" class=" col-md-8 col-lg-6 col-form-label">Afficher le gâteau avec l'identifiant :</label>
        <div class=" col-md-8 col-lg-6">
            <input class="form-control" required="required" type="text" value="" id="idx">
        </div>
    </div>
    <div class="col-md-8 col-lg-6">
        <button class="btn btn-primary" id="btn-get-gateau">Valider</button>
    </div>
    <br>
    <div class="col-md-8 col-lg-6">
        <div id="result"></div>
    </div>
    <br><br>


    <h3>Affichage d'une liste en GET</h3>
    <div class="form-group form-group-nom ">
        <label for="result2" class=" col-md-8 col-lg-6 col-form-label">Afficher les gâteaux</label>
    </div>
    <div class="col-md-8 col-lg-6">
        <button class="btn btn-primary" id="btn-get-gateaux">Valider</button>
    </div>
    <br>
    <div class="col-md-8 col-lg-6">
        <div id="result2"></div>
        <table id="table-gateau"></table>
    </div>

</div>
<script src="js/index.js?v=1"></script>
</body>
</html>
  

client.js

$(document).ready(function () {
    
     //POST /gateau?id=x&nom=y
     $('#btn-insert-gateau').click(function () {
        let id = $('#id').val();
        let nom = $('#nom').val();
        $.ajax({
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            url: "http://localhost/api-gateau/gateau?id=" + id + "&nom=" + nom,
            success: function (data) {
                //gateau enregistré, on préférera l'ajout d'un messaqge dans un div
                alert("gateau enregistré");
            }
        });
    });

   //GET  /gateau/:id
   $('#btn-get-gateau').click(function () {
        let idx = $('#idx').val();
        $.getJSON("http://localhost/api-gateau/gateau/" + idx, function (data) {
            $('#result').html(data[0].nom);

        });
    });
 
    //GET /gateaux
    $('#btn-get-gateaux').click(function () {
        $('#table-gateau').bootstrapTable({
            url: 'http://localhost/api-gateau/gateaux',
            columns: [{
                field: 'id',
                title: 'Item ID'
            }, {
                field: 'nom',
                title: 'Item Name'
            },]
        });
    });
});