}); $app->get('/devices/{deviceId}', function (Request $request, Response $response) use($device) { $result = ['status' => 'error', 'message' => 'Runtime Error']; try { $deviceData = $device->fetchById($request->getAttribute('deviceId')); $result = ['status' => 'success', 'data' => $deviceData]; } catch (\Exception $ex) { $result['message'] = $ex->getMessage(); } return new JsonModel($result); }); $app->put('/devices/{deviceId}', function (Request $request, Response $response) use($device) { $result = ['status' => 'error', 'message' => 'Runtime Error']; try { $data = $request->getParsedBody(); if (is_array($data)) { if (isset($data['port']) && isset($data['status'])) { $result = ['status' => 'success']; $device->updateByPortId($request->getAttribute('deviceId'), $data['port'], $data['status']); } else { $result['message'] = 'Bad Request'; } } else { $result['message'] = 'Bad Request'; } } catch (\Exception $ex) { $result['message'] = $ex->getMessage(); } return new JsonModel($result); }); $app->run();
frameworks are available online in a separate repository. </p> <p><a href="https://github.com/codeguy/Slim-Extras" target="_blank">Browse the Extras Repository</a></p> </section> </body> </html> EOT; echo $template; }); // POST route $app->post('/post', function () { echo 'This is a POST route'; }); // PUT route $app->put('/put', function () { echo 'This is a PUT route'; }); // PATCH route $app->patch('/patch', function () { echo 'This is a PATCH route'; }); // DELETE route $app->delete('/delete', function () { echo 'This is a DELETE route'; }); /** * Step 4: Run the Slim application * * This method should be called last. This executes the Slim application * and returns the HTTP response to the HTTP client. */
} return true; }; $reservationDataValidator = function (array $reservationData = null) { if ($reservationData === null || !isset($reservationData['email']) || !isset($reservationData['bookId'])) { return false; } return true; }; //Add book to library $app->put('/books/{bookId}', function (ServerRequestInterface $request, ResponseInterface $response, $args = []) use($library, $app, $bookDataValidator) { $bookId = Uuid::fromString($args['bookId']); $requestBody = $request->getParsedBody(); if ($bookDataValidator($requestBody) == false) { return $response->withHeader('Content-Type', 'application/json')->withStatus(400); } $responseBody = $response->getBody(); $responseBody->write(json_encode(['id' => (string) $bookId])); $library->addBook($bookId, $requestBody['title'], $requestBody['authors'], $requestBody['isbn']); return $response->withHeader('Content-Type', 'application/json')->withStatus(201)->withBody($responseBody); }); //List books in library $app->get('/books', function (ServerRequestInterface $request, ResponseInterface $response, $args = []) use($library, $app) { $page = 1; $booksPerPage = null; $query = $request->getQueryParams(); if (isset($query['page'])) { $page = $query['page']; } if (isset($query['booksPerPage'])) { $booksPerPage = $query['booksPerPage'];
global $app_config; $app_config = parse_ini_file('config.ini', true); $app->get('/version', function ($request, $response, $args) { $id = array('service' => 'Going Dutch API', 'version' => '0.1', 'uid' => \Middleware\Authenticate::$requestUid); $response->write(json_encode($id)); return $response; })->add($auth); $app->get('/groups', function ($request, $response, $args) { $member = new \Models\Member(); $response->write($member->getGroupsBalance(\Middleware\Authenticate::$requestUid)); $newResponse = $response->withHeader('Content-type', 'application/json'); return $newResponse; })->add($auth); $app->put('/groups', function ($request, $response, $args) { $member = new \Models\Group(); $response->write($member->updateGroupDetails($request->getParsedBody(), \Middleware\Authenticate::$requestUid)); $newResponse = $response->withHeader('Content-type', 'application/json'); return $newResponse; })->add($auth); $app->get('/users', function ($request, $response, $args) { $member = new \Models\Member(); $response->write($member->getDetailsMembersInGroups(\Middleware\Authenticate::$requestUid)); $newResponse = $response->withHeader('Content-type', 'application/json'); return $newResponse; })->add($auth); $app->get('/user/{uid}/details', function ($request, $response, $args) { $member = new \Models\Member(); $response->write($member->getMemberDetails($args['uid'], \Middleware\Authenticate::$requestUid)); $newResponse = $response->withHeader('Content-type', 'application/json'); return $newResponse; })->add($auth); $app->put('/user/{uid}/details', function ($request, $response, $args) {
} return $response; }); $app->put('/api/wines/{id}', function (Request $request, Response $response, $args) { $request = $app->request(); $body = $request->getBody(); // or $allPutVars = $app->request->put(); $input = json_decode($body); $sql = "UPDATE wine SET name=:name, grapes=:grapes, country=:country, region=:region, year=:year, description=:description WHERE id=:id"; $id = $args['id']; try { $db = thisConnection(); $stmt = $db->prepare($sql); $stmt->bindParam("name", $input->name); $stmt->bindParam("grapes", $input->grapes); $stmt->bindParam("country", $input->country); $stmt->bindParam("region", $input->region); $stmt->bindParam("year", $input->year); $stmt->bindParam("description", $input->description); $stmt->bindParam("id", $id); $stmt->execute(); $response->getBody()->write(json_encode($input)); } catch (PDOException $e) { $response->getBody()->write('{"error":' . $e->getMessage() . '}'); die; } return $response; }); $app->delete('/api/wines/{id}', function (Request $request, Response $response, $args) { $id = $args['id']; try {
}); /* Handle get user info */ $app->get('/user/{id:[0-9]+}/info', function ($request, $response, $args) { $token = parseToken($request); $friend_id = $args['id']; return UsersInfo::get($response, $token, $friend_id); }); /* Handle get my info */ $app->get('/user/me/info', function ($request, $response) { $token = parseToken($request); return UsersInfo::get($response, $token, null); }); /* Handle update my info */ $app->put('/user/me/info', function ($request, $response) { $token = parseToken($request); $data = parseJsonBody($request); return UsersInfo::update($response, $token, $data); }); /* Handle get my posts */ $app->get('/user/me/posts', function ($request, $response) { $token = parseToken($request); return Posts::all($response, $token, null); }); /* Handle get user posts */ $app->get('/user/{id:[0-9]+}/posts', function ($request, $response, $args) { $token = parseToken($request); $friend_id = $args['id']; return Posts::all($response, $token, $friend_id); }); /* Handle get post */ $app->get('/post/{id}', function ($request, $response, $args) {
$resource = AbstractResource::load($resource, $request, $response, $this); return $response->withJson($formatter->getSuccess($resource->post())); } catch (StatusException $e) { return $response->withJson($formatter->getFailure($e->getMessage()), $e->getCode()); } catch (Exception $e) { return $response->withStatus(500); } }); // Put $app->put('/{resource}/{id}', function (ServerRequestInterface $request, Response $response, $resource, $id = null) { /** * @var ResponseDataFormatter $formatter */ $formatter = $this->get('dataFormatter'); try { $resource = AbstractResource::load($resource, $request, $response, $this); return $response->withJson($formatter->getSuccess($resource->put($id))); } catch (StatusException $e) { return $response->withJson($formatter->getFailure($e->getMessage()), $e->getCode()); } catch (Exception $e) { return $response->withStatus(500); } }); // Delete $app->delete('/{resource}/{id}', function (ServerRequestInterface $request, Response $response, $resource, $id = null) { /** * @var ResponseDataFormatter $formatter */ $formatter = $this->get('dataFormatter'); try { $resource = AbstractResource::load($resource, $request, $response, $this); $resource->delete();
return $jsonResponse; } catch (PDOException $e) { echo '{"error":{"text":' . $e->getMessage() . '}}'; } }); $app->put('/v1/bookmarks/{id}', function (Request $request, Response $response) { $sql = "UPDATE bookmarks SET name=:name, description=:description, url=:url WHERE id=:id"; try { $id = $request->getAttribute('id'); $parsedBody = $request->getParsedBody(); echo $parsedBody; $db = getDB(); $stmt = $db->prepare($sql); $stmt->bindParam("name", $parsedBody['name']); $stmt->bindParam("description", $parsedBody['description']); $stmt->bindParam("url", $parsedBody['url']); $stmt->bindParam("id", $id); $stmt->execute(); $db = null; $jsonResponse = $response->withHeader('Content-type', 'application/json'); $jsonResponse->getBody()->write(true); return $jsonResponse; } catch (PDOException $e) { echo '{"error":{"text":' . $e->getMessage() . '}}'; } }); $app->delete('/v1/bookmarks/{delete_id}', function (Request $request, Response $response) { $sql = "DELETE FROM bookmarks WHERE id=:id"; try { $delete_id = $request->getAttribute('delete_id'); $db = getDB();
$db->run($qry, 0); // return id data to client $qry = "SELECT * FROM user WHERE user_ra = " . $args['ra']; $output = $db->run($qry, 1); $response->write($output); return $response; }); // update User $app->put('/users/{ra}&{nome}', function ($request, $response, $args) use($db) { if ($args['ra'] != 0) { // Update user query $qry = "UPDATE user SET username = '******'nome'] . "' WHERE user_ra = " . $args['ra']; $db->run($qry, 0); // return id data to client $qry = "SELECT * FROM user WHERE user_ra = " . $args['ra']; $output = $db->run($qry, 1); $response->write($output); return $response; } else { $response->write("Test Player cannot be updated. Please insert another RA."); return $response; } }); // delete User $app->delete('/users/{ra}', function ($request, $response, $args) use($db) { if ($args['ra'] != 0) { // Remove user from castle $qry = "UPDATE castle_owners SET user_ra = 0 WHERE user_ra = " . $args['ra']; $db->run($qry, 0); // Delete user query $qry = "DELETE FROM user WHERE `user_ra` = " . $args['ra'];
$app->put('/updateContact', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) use($app) { try { if (!has_access($request)) { return access_denied($response); } $requestData = $request->getBody()->getContents(); $data = json_decode($requestData, true); $contact = contactParser($data); if ($contact->getId() == null || $contact->getId() == -1) { return error($response, 'UPDATE A CONTACT WITH NO ID IS NOT POSSIBLE'); } if ($contact->getExchangeId() == null || $contact->getExchangeId() == -1 || $contact->getExchangeId() == "") { return error($response, 'UPDATE A CONTACT WITH NO EXCHANGE ID IS NOT POSSIBLE'); } $contactService = new ContactService(); $exchangeService = new ExchangeService(); $deletedFromExchange = $exchangeService->deleteContact($contact); if (!$deletedFromExchange) { return error($response, 'ERROR DURING UPDATING IN EXCHANGE'); } if (!$exchangeService->addContact($contact)) { return error($response, 'ERROR DURING UPDATING IN EXCHANGE'); } if (!$contactService->updateContact($contact)) { return error($response, 'ERROR DURING UPDATING IN DATABASE'); } return $response->write(json_encode("ok", true)); } catch (Exception $e) { error_log($e->getMessage()); } return error($response, ' UPDATE CONTACT UNKNOWN ERROR'); });
$app->put('/api/activities/{id:\\d+}', function (Request $request, Response $response, array $args) { $data = $request->getParsedBody(); $activity = []; $activity['id'] = $args['id']; $activity['title'] = $data['title']; $activity['started_at'] = $data['started_at']; $activity['finished_at'] = $data['finished_at']; $activity['tags'] = $data['tags']; try { $this->db->beginTransaction(); $sth = $this->db->prepare('UPDATE activity SET title = ?, started_at = ?, finished_at = ? WHERE id = ?'); $sth->execute([$activity['title'], $activity['started_at'], $activity['finished_at'], $activity['id']]); $sth = $this->db->prepare('DELETE FROM activity_tag WHERE activity_id = ?'); $sth->execute([$activity['id']]); if (count($activity['tags']) > 0) { $tags = []; foreach ($activity['tags'] as $tag) { $sth = $this->db->prepare('INSERT INTO tag (title) VALUES (?) ON CONFLICT DO NOTHING RETURNING id'); $sth->execute([$tag]); $id = $sth->fetchColumn(); if ($id === false) { $sth = $this->db->prepare('SELECT id FROM tag WHERE LOWER(title) = LOWER(?)'); $sth->execute([$tag]); $id = $sth->fetchColumn(); } $tags[] = ['id' => $id, 'title' => $tag]; } $placeholders = substr(str_repeat('(?, ?), ', count($activity['tags'])), 0, -2); $sth = $this->db->prepare("INSERT INTO activity_tag (activity_id, tag_id) VALUES {$placeholders}"); $params = []; foreach ($tags as $tag) { array_push($params, $activity['id'], $tag['id']); } $sth->execute($params); } $this->db->commit(); return $response->withJson($activity); } catch (PDOException $e) { $this->db->rollBack(); return $response->withJson(['error' => $e->getMessage()], 500); } });
//routes $app->get('/user/', function ($request, $response, $args) { echo 'list<br>'; $controller = new LoginController(); $logins = $controller->getList(); print_r($logins); }); $app->get('/user/{id}', function ($request, $response, $args) { echo 'one<br>'; $controller = new LoginController(); $login = $controller->getLogin($args['id']); print_r($login); }); $app->put('/user/', function ($request, $response, $args) { $l = $request->getParsedBody()['login']; $controller = new LoginController(); $resp = $controller->addLogin($l); print_r($resp); }); $app->post('/user/', function ($request, $response, $args) { $l = $request->getParsedBody()['login']; $controller = new LoginController(); $resp = $controller->editLogin($l); print_r($resp); }); $app->delete('/user/{id}', function ($request, $response, $args) { $controller = new LoginController(); $resp = $controller->removeLogin($args['id']); print_r($resp); }); $app->run();
$newContact = $request->getParsedBody(); $contact = new Contact(); $contact->name = $newContact['name']; $contact->email = $newContact['email']; $contact->number = $newContact['number']; $contact->save(); return $response; }); $app->get('/contacts', function ($request, $response, $args) { $response->withJson(Contact::all()); return $response; }); $app->get('/contacts/{id}', function ($request, $response, $args) { $contact = Contact::find($args['id']); $response->write($contact->toJson()); return $response; }); $app->put('/contacts/{id}', function ($request, $response, $args) { $editedContact = $request->getParsedBody(); $contact = Contact::find($args['id']); $contact->name = $editedContact['name']; $contact->email = $editedContact['email']; $contact->number = $editedContact['number']; $contact->save(); return $response; }); $app->delete('/contacts/{id}', function ($request, $response, $args) { Contact::delete($args['id']); return $response; }); $app->run();
$beard = $beardDB->getBeard($id); return renderJSON($response, 200, $beard); }); // Show action $app->get('/beards/{id}', function ($request, $response, $args) { $id = $args['id']; $beardDB = new Beard(); $beard = $beardDB->getBeard($id); return $this->view->render($response, 'show.html.php', ['beard' => $beard]); }); // Update action $app->put('/beards/{id}', function ($request, $response, $args) { $id = $args['id']; $beardDB = new Beard(); $beard = $beardDB->updateBeard($id); if ($beard) { return $response->withStatus(302)->withHeader('Location', '/slimapi/index.php/beards'); } else { return $response->withStatus(500)->withHeader('Location', '/slimapi/index.php/beards'); } }); // Create action .json $app->post('/beards.json', function ($request, $response) { $body = $request->getParsedBody(); // $_POST associative array $beardDb = new Beard(); $beard = $beardDb->createBeard($body); return renderJSON($response, 201, $beard); }); // Create action $app->post('/beards', function ($request, $response) { $body = $request->getParsedBody();
$app->put('/{id}', function (Request $request, Response $response) { $id = false; try { //Recup data $idWine = $request->getAttribute('id'); $mediaType = $request->getMediaType(); $body = $request->getBody(); if ($mediaType == 'application/xml') { $input = simplexml_load_string($body); } elseif ($mediaType == 'application/json') { $input = json_decode($body); } //Initializing data $name = $input->nameVal; $grapes = $input->grapesVal; $country = $input->countryVal; $region = $input->regionVal; $year = $input->yearVal; $description = $input->textVal; //Load the wine by ID $idWine = (int) $idWine; $wineToUpdate = R::load('wine', $idWine); //Add properties $wineToUpdate->name = $name; $wineToUpdate->grapes = $grapes; $wineToUpdate->country = $country; $wineToUpdate->region = $region; $wineToUpdate->year = $year; $wineToUpdate->description = $description; //Store in the database $id = R::store($wineToUpdate); //Return data if ($id !== false) { echo "valid"; } else { echo "unvalid"; } //IF 404 - 500 } catch (ResourceNotFoundException $e) { echo "404"; } catch (Exception $e) { echo "400"; } });
$resultat = $stmt->execute(array(':name' => strtoupper($_POST['name']), ':grapes' => $_POST['grapes'], ':country' => $_POST['country'], ':region' => $_POST['region'], ':year' => $_POST['year'], ':description' => $_POST['description'], ':picture' => 'default.jpg')); // Si l'ajout s'est bien passé, on retourne un message de réussite if ($resultat !== false) { return json_encode(['reponse' => 'Le vin a bien été ajouté']); } }); // Modifie les données du vin dont on possède l'id $app->put('/api/wines/{id}', function (Request $request, Response $response, $args) { // Connection à la DB $pdo = database(); // On tente de modifier dans la DB le vin dont on possède l'id $stmt = $pdo->prepare('UPDATE wine SET name=:name, grapes=:grapes, country=:country, region=:region, year=:year, description=:description WHERE id=:id'); $resultat = $stmt->execute(array(':name' => strtoupper($_REQUEST['name']), ':grapes' => $_REQUEST['grapes'], ':country' => $_REQUEST['country'], ':region' => $_REQUEST['region'], ':year' => $_REQUEST['year'], ':description' => $_REQUEST['description'], ':id' => $args['id'])); // Si la modification s'est bien passée, on retourne un message de réussite if ($resultat !== false) { return json_encode(['reponse' => 'Le vin a bien été modifié']); } }); // Supprime le vin dont on possède l'id $app->delete('/api/wines/{id}', function (Request $request, Response $response, $args) { // Connection à la DB $pdo = database(); // On tente de supprimer dans la DB le vin dont on possède l'id $stmt = $pdo->prepare('DELETE FROM wine WHERE id = :id'); $resultat = $stmt->execute(array(':id' => $args['id']));
<?php require 'vendor/autoload.php'; $app = new Slim\App(); // $verbs = array('GET', 'POST', 'PUT', 'DELETE'); // $app->map(array('PUT'),'/home',function($request,$response,$args){ // echo 'yes'; // }); $app->put('/home', function ($request, $response, $args) { echo 'something new'; }); $app->run();
echo "RAUMSUCHE API"; }); // === USERS === $app->get('/users', function ($request, $response, $args) { $users = User::getUsers(); echo json_encode($users); }); $app->get('/users/{id}', function ($request, $response, $args) { $user = User::getUserByMtrklNr($args['id']); echo json_encode($user); }); $app->put('/register', function ($request, $response, $args) { $put = json_decode($request->getBody()); $password = rand_passwd(); // make it a PHP associative array $putArray = get_object_vars($put); $user = new User($putArray['mtklNr'], password_hash($password, PASSWORD_DEFAULT), $putArray['name'], $putArray['faculty']); sendEmail($putArray['mtklNr'], $password); $user->add(); echo json_encode($user); }); $app->post('/users/{id}', function ($request, $response, $args) { $server_params = $request->getServerParams(); if (preg_match("/Basic\\s+(.*)\$/i", $server_params["REDIRECT_HTTP_AUTHORIZATION"], $matches)) { list($user, $password) = explode(":", base64_decode($matches[1])); } if ($args['id'] == $user) { $post = json_decode($request->getBody()); $postArray = get_object_vars($post); $user = new User($args['id'], $postArray['password'], $postArray['name'], $postArray['faculty']); $user->update(); echo json_encode($user);
$app->add(new \Slim\HttpCache\Cache('public', $container['config']['cache_lifetime'])); $app->get('/', function ($request, $response) { $domain = $this->environment['HTTP_HOST']; try { $this->sites->load(); $target = $this->sites->lookup($domain); } catch (\Exception $e) { $target = (object) array('redirect' => $this->config['sites']['default_url']); } if (empty($target->status)) { $target->status = $this->config['sites']['default_status']; } $response = $response->withStatus($target->status)->withAddedHeader('Location', $target->redirect); return $response; }); $app->put('/update', function ($request, $response) { /* if ('HTTPS' != $request->getUri()->getScheme()) { return $response->withStatus(400); } */ $key = $this->config['shared_key']; $json = $request->getParsedBody(); if ($json->key != $key) { return $response->withStatus(403); } $this->sites->update($json->sites); $response = $response->withStatus(200)->withAddedHeader('Content-type', 'application/json'); $response->write(json_encode(array('status' => 'ok'))); }); $app->run();
echo "3:".$myvar3; }); */ $app->get('/servicios', 'getServicios'); $app->get('/servicios/{id}', function (Request $req, Response $res) { $id = $req->getAttribute('id'); $rs_data = getServicio($id); if ($rs_data === false) { return $res->withStatus(400)->withHeader('Content-Type', 'application/json')->write(json_encode(responseHandler(400, 'ERR_DATABASE', 'Error al consultar la base de datos.'))); } else { return $res->withStatus(200)->withHeader('Content-Type', 'application/json')->write(json_encode(responseHandler(200, '', '', getServicio($id)))); } }); $app->get('/servicios/search/:query', 'findServicioByName'); $app->post('/servicios', 'addServicio'); $app->put('/servicios/:id', 'updateServicio'); $app->delete('/servicios/:id', 'deleteServicio'); $app->post('/datos', function (Request $req, Response $res, $args = []) { $args = $req->getParsedBody(); //var_dump($args); //echo $args['usr']; /* return $res->withHeader( 'Content-Type', 'application/json' ); */ //$cnxn = getCnxn(); //var_dump($cnxn); return $res->withStatus(200)->withHeader('Content-Type', 'application/json')->write(json_encode(array("success" => 1, "data" => $args))); });
<?php /** * Created by PhpStorm. * User: RDuuke * Date: 03/11/2015 * Time: 08:07 PM */ use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamInterface; $app = new Slim\App(); $app->get('/users', '\\RDuuke\\Mdn\\Controllers\\UsersController:index'); $app->post('/users', '\\RDuuke\\Mdn\\Controllers\\UsersController:store'); $app->get('/users/{id}', '\\RDuuke\\Mdn\\Controllers\\UsersController:show'); $app->put('/users/{id}', '\\RDuuke\\Mdn\\Controllers\\UsersController:update'); $app->delete('/users/{id}', '\\RDuuke\\Mdn\\Controllers\\UsersController:destroy'); $app->run();
return Responder::getJsonResponse(Player::statistics()->where(['id' => $args['playerId'], 'team_id' => $args['id']])->get(), $response); }); $api->get('/teams/{id}/coach', function ($request, $response, $args) { return Responder::getJsonResponse(Team::with('coach')->where(['id' => $args['id']])->get(), $response); }); $api->get('/leagues', function ($request, $response, $args) { return Responder::getJsonResponse(League::all(), $response); }); $api->get('/leagues/{id}', function ($request, $response, $args) { return Responder::getJsonResponse(League::with('rounds')->where(['id' => $args['id']])->first(), $response); }); $api->get('/leagues/{id}/rounds/{roundId}', function ($request, $response, $args) { return Responder::getJsonResponse(LeagueRound::complete()->where(['id' => $args['roundId']])->first(), $response); }); $api->put('/leagues/{id}/rounds/{roundId}/simulate', function ($request, $response, $args) { return Responder::getJsonResponse(MatchSimulator::simulateRound($args['roundId']), $response); }); $api->get('/matches', function ($request, $response, $args) { return Responder::getJsonResponse(Match::teams()->get(), $response); }); $api->post('/matches', function ($request, $response, $args) { $json = $request->getBody(); $json = json_decode($json, true); return Responder::getJsonResponse(Match::create($json), $response); }); $api->get('/matches/{id}', function ($request, $response, $args) { return Responder::getJsonResponse(Match::complete()->where(['id' => $args['id']])->first(), $response); }); $api->get('/matches/{id}/result', function ($request, $response, $args) { $result = MatchResult::complete()->where(['id' => $args['id']])->first(); return Responder::getJsonResponse($result, $response);
$response->getBody()->write($output['options']); return $response; }); // select all languages usind id wia ajax (service handler) $app->get("/languages/{id}/", function ($request, $response, $args) use($link) { //$post=$request->getParsedBody(); $output = getLanguages($args['id']); $response->getBody()->write($output['options']); return $response; }); /* Edit country using Id */ $app->put("/country/{id}/", function ($request, $response, $args) use($link) { $put = $request->getParsedBody(); $name = clearStr($put['Name']); $id = getId($args['id'], 'countries'); if ($id && updateId($id['id'], 'countries', $name)) { return $response->withJson(array('status' => 1, 'message' => "Country updated sucsesfully", 'name' => $name, 'put' => $put)); } else { return $response->withJson(array('status' => 0, 'message' => "Country ID does not exists")); } }); /* Edit city using Id */ $app->put("/country/{idCountry}/city/{idCity}/", function ($request, $response, $args) use($link) { $put = $request->getParsedBody(); $idCity = getId($args['idCity'], 'cities'); $idCountry = getId($args['idCountry'], 'countries'); $name = clearStr($put['Name']); if ($idCity && $idCountry) { updateId($idCity['id'], 'cities', $name); return $response->withJson(array('status' => 1, 'message' => "Country updated sucsesfully", 'args' => $args, 'put' => $put)); } else { return $response->withJson(array('status' => 0, 'message' => "Country ID {$args['idCountry']} or City {$args['idCity']} does not exists"));
$stmt->bindValue(':time_measurement', $meeting['time_measurement']); $stmt->execute(); $meeting['meeting_id'] = $db->lastInsertId(); $response->getBody()->write(json_encode($meeting)); return $response; }); $app->put('/meeting/{id}', function ($request, $response, $args) { $meeting = $request->getBody(); $db = $this->dbConnection; $sql = 'UPDATE meeting_information SET meeting_name=:meeting_name, meeting_short_name=:meeting_short_name, organizer=:organizer, presenter=:presenter, place=:place, meeting_nr=:meeting_nr, category=:category, stadium=:stadium, time_measurement=:time_measurement WHERE meeting_id=:meeting_id;'; $stmt = $db->prepare($sql); $stmt->bindValue(':meeting_id', $args['id'], PDO::PARAM_INT); $stmt->bindValue(':meeting_name', $meeting['meeting_name']); $stmt->bindValue(':meeting_short_name', $meeting['meeting_short_name']); $stmt->bindValue(':organizer', $meeting['organizer']); $stmt->bindValue(':presenter', $meeting['presenter']); $stmt->bindValue(':place', $meeting['place']); $stmt->bindValue(':meeting_nr', $meeting['meeting_nr']); $stmt->bindValue(':category', $meeting['category']); $stmt->bindValue(':stadium', $meeting['stadium']); $stmt->bindValue(':time_measurement', $meeting['time_measurement']); $stmt->execute(); $response->getBody()->write(json_encode($meeting)); return $response; }); $app->delete('/meeting/{id}', function ($request, $response, $args) { $db = $this->dbConnection; $sql = "DELETE FROM meeting_information WHERE meeting_id=:meeting_id limit 1;"; // TODO constraints to delete everything from db $stmt = $db->prepare($sql); $stmt->bindValue(":meeting_id", $args['id'], PDO::PARAM_INT);
# IMPORT require __DIR__ . "/vendor/autoload.php"; use KarabowId\Api\Orm\OrmManager; use KarabowId\Api\ParamHandler; use KarabowId\Api\Messages; # SETUP $configuration = ['settings' => ['displayErrorDetails' => true]]; $config = new \Slim\Container($configuration); $app = new Slim\App($config); $ormManager = new OrmManager(); $app->any("/", function ($request, $response, $args) { $reponse->getBody()->write("No Request Made. Should we throw an exception? or just tell the user to go learn how to consume this api?"); }); # CREATE NEW USER $app->post("/user/new", function ($request, $response, $args) use($app) { return $response; }); # GET USER INFO $app->get("/user", function ($request, $response, $args) use($app) { return $response; }); # MODIFY USER INFO $app->put("/user/edit", function ($request, $response, $args) use($app) { return $response; }); # DELETE USER FROM DB $app->delete("/user/delete", function ($request, $response, $args) use($app) { return $response; }); # RUN $app->run();
<?php require __DIR__ . '/../vendor/autoload.php'; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; $app = new \Slim\App(); //List of posts $app->get('/posts', function (ServerRequestInterface $request, ResponseInterface $response) { $posts = [['title' => 'Example post 1', 'content' => 'Aliquam erat volutpat.'], ['title' => 'Example post 2', 'content' => 'Vestibulum suscipit nulla quis orci.'], ['title' => 'Example post 3', 'content' => 'Phasellus magna.'], ['title' => 'Example post 4', 'content' => 'Sed augue ipsum, egestas nec, vestibulum et, malesuada adipiscing, dui.']]; $query = $request->getQueryParams(); if (isset($query['page']) && $query['page'] >= 1) { $page = $query['page']; $postsPerPage = 2; $offset = ($page - 1) * $postsPerPage; $length = $postsPerPage; $posts = array_slice($posts, $offset, $length); } $responseBody = $response->getBody(); $responseBody->write(json_encode($posts)); return $response->withHeader('Content-Type', 'application/json')->withStatus(200)->withBody($responseBody); }); //Add new post $app->put('/posts/{postId}', function (ServerRequestInterface $request, ResponseInterface $response, $args = []) { $postId = $args['postId']; $responseBody = $response->getBody(); $responseBody->write(json_encode(['id' => $postId])); return $response->withHeader('Content-Type', 'application/json')->withStatus(201)->withBody($responseBody); }); return $app;