Please disable Adblockers and enable JavaScript for domain CEWebS.cs.univie.ac.at! We have NO ADS, but they may interfere with some of our course material.

REST_Example

This is just an example - you can use any library/programming language you want or even handle the HTTP requests yourself. 
 
Example for handling HTTP requests with PHP framework «Slim» (for installation see web page) with hard-coded data: 
 
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
 
require __DIR__ . '/vendor/autoload.php';
 
 
 
$app = AppFactory::create();
$app->setBasePath("/your/base/path");
 
$app->get('', function (Request $request, Response $response, $args) {
  $response->getBody()->write("Hello world!");
  return $response;
});
 
 
$app->get('/', function (Request $request, Response $response, $args) {
  $response->getBody()->write("Hello world!");
  return $response;
});
 
$app->get('/tv_series', function (Request $request, Response $response, $args) {
  $hoc = new stdClass();
  $hoc->id = 0;
  $hoc->title = "House of Cards";
 
  $himym = new stdClass();
  $himym->id = 1;
  $himym->title = "How I Met Your Mother";
  
  $mh = new stdClass();
  $mh->id = 2;
  $mh->title = "Money Heist";
  
  $f = new stdClass();
  $f->id = 3;
  $f->title = "Friends";
  
  $tbbt = new stdClass();
  $tbbt->id = 4;
  $tbbt->title = "The Big Bang Theory";
  
  $mitm = new stdClass();
  $mitm->id = 5;
  $mitm->title = "Malcolm in the Middle";
  
  $tv_series= array($hoc, $himym, $mh, $f, $tbbt, $mitm);
  
  $response = $response->withHeader('Content-Type','application/json');
  $response->getBody()->write(json_encode($tv_series));
  return $response;
});
 
$app->get('/tv_series/{id}', function (Request $request, Response $response, $args) {
  $hoc = new stdClass();
  $hoc->id = 0;
  $hoc->title = "House of Cards";
 
  $himym = new stdClass();
  $himym->id = 1;
  $himym->title = "How I Met Your Mother";
  
  $mh = new stdClass();
  $mh->id = 2;
  $mh->title = "Money Heist";
  
  $f = new stdClass();
  $f->id = 3;
  $f->title = "Friends";
  
  $tbbt = new stdClass();
  $tbbt->id = 4;
  $tbbt->title = "The Big Bang Theory";
  
  $mitm = new stdClass();
  $mitm->id = 5;
  $mitm->title = "Malcolm in the Middle";
  
  $tv_series= array($hoc, $himym, $mh, $f, $tbbt, $mitm);
 
  $id = intval($args['id']);
  if($id < count($tv_series) && strval($id) === $args['id']) {
    $response = $response->withHeader('Content-Type','application/json');
    $response->getBody()->write(json_encode($tv_series[$id]));
    return $response;
  }
  else {
    return $response->withStatus(404);
  }
});
 
$app->run();
Letzte Änderung: 21.05.2021, 14:32 | 274 Worte