} } $app->response->setStatus($output['code']); $app->response->setBody(json_encode($output)); }); // Edit (move and rename) a folder $app->put('/api/folders/(:path+)', function ($path = array()) use($app, $db) { list($user, $tenant, $output) = apiAuthorization($db, $app->getCookie('unetlab_session')); if ($user === False) { $app->response->setStatus($output['code']); $app->response->setBody(json_encode($output)); return; } if (!in_array($user['role'], array('admin', 'editor'))) { $app->response->setStatus($GLOBALS['forbidden']['code']); $app->response->setBody(json_encode($GLOBALS['forbidden'])); return; } // TODO must check before using p name and p path $event = json_decode($app->request()->getBody()); $s = '/' . implode('/', $path); $p = json_decode(json_encode($event), True); $output = apiEditFolder($s, $p['path']); $app->response->setStatus($output['code']); $app->response->setBody(json_encode($output)); }); // Add a new folder $app->post('/api/folders', function () use($app, $db) { list($user, $tenant, $output) = apiAuthorization($db, $app->getCookie('unetlab_session')); if ($user === False) { $app->response->setStatus($output['code']); $app->response->setBody(json_encode($output));
/** * Test PUT route */ public function testPutRoute() { \Slim\Environment::mock(array('REQUEST_METHOD' => 'PUT', 'SCRIPT_NAME' => '/foo', 'PATH_INFO' => '/bar')); $s = new \Slim\Slim(); $mw1 = function () { echo "foo"; }; $mw2 = function () { echo "bar"; }; $callable = function () { echo "xyz"; }; $route = $s->put('/bar', $mw1, $mw2, $callable); $s->call(); $this->assertEquals('foobarxyz', $s->response()->body()); $this->assertEquals('/bar', $route->getPattern()); $this->assertSame($callable, $route->getCallable()); }
$slim->put('/', function () use($slim) { $body = $slim->request->getBody(); if (!isset($body) || strlen($body) == 0) { $app->response()->status(401); // not authorised } else { $plist = new \CFPropertyList\CFPropertyList(); $plist->parse($body); $message = $plist->toArray(); $udid = $message["UDID"]; $device = find_device($udid); // do we have any commands for this device? if (isset($message["CommandUUID"])) { // responding to message // find my command on the queue and move it $queue_command = find_queue_command($message["CommandUUID"]); if (isset($queue_command)) { delete_queue_command($queue_command); } } else { // we're just responding to an initial request log_device_status($device, $message["Status"]); } $command = next_command_for_device($device); if (isset($command) > 0) { // send back the first command $inner_command = $command["command"]; $res_plist = new \CFPropertyList\CFPropertyList(); $res_plist->add($dict = new \CFPropertyList\CFDictionary()); $request_dict = new \CFPropertyList\CFDictionary(); if ($inner_command["Command"]["RequestType"] == "DeviceLock") { $request_dict->add('RequestType', new \CFPropertyList\CFString("DeviceLock")); } $dict->add("Command", $request_dict); $dict->add("CommandUUID", new \CFPropertyList\CFString($inner_command["CommandUUID"])); echo $res_plist->toXML(true); } else { // empty plist for you $res_plist = new \CFPropertyList\CFPropertyList(); $res_plist->add($dict = new \CFPropertyList\CFDictionary()); echo $res_plist->toXML(true); } } });
$app->put('/people/:userid', function ($userid) use($app, $person) { if (!$person->ContactAdmin) { $response['error'] = true; $response['errorcode'] = 400; $response['message'] = "Insufficient privilege level"; echoResponse(200, $response); $app->stop(); } // Only one field is required - all others are optional verifyRequiredParams(array('UserID')); $response = array(); $p = new People(); $p->UserID = $app->request->put('UserID'); if ($p->GetPersonByUserID()) { $response['error'] = true; $response['errorcode'] = 403; $response['message'] = __("UserID already in database. Use the update API to modify record."); echoResponse(200, $response); } else { // Slim Framework will simply return null for any variables that were not passed, so this is safe to call without blowing up the script foreach ($p as $prop) { $p->{$prop} = $app->request->put($prop); } $p->Disabled = false; $p->CreatePerson(); if ($p->PersonID == false) { $response['error'] = true; $response['errorcode'] = 403; $response['message'] = __("Unable to create People resource with the given parameters."); echoResponse(200, $response); } else { $response['error'] = false; $responde['errorcode'] = 200; $response['message'] = __("People resource created successfully."); $response['people'] = $p; echoResponse(200, $response); } } });
$consulta->execute(array(':id' => $idusuario)); if ($consulta->rowCount() == 1) { echo json_encode(array('estado' => true, 'mensaje' => 'El usuario ' . $idusuario . ' ha sido borrado correctamente.')); } else { echo json_encode(array('estado' => false, 'mensaje' => 'ERROR: ese registro no se ha encontrado en la tabla.')); } }); // Actualización de datos de usuario (PUT) $app->put('/usuarios/:idusuario', function ($idusuario) use($db, $app) { // Para acceder a los datos recibidos del formulario $datosform = $app->request; // Los datos serán accesibles de esta forma: // $datosform->post('apellidos') // Preparamos la consulta de update. $consulta = $db->prepare("update soporte_usuarios set nombre=:nombre, apellidos=:apellidos, email=:email \n\t\t\t\t\t\t\twhere idusuario=:idusuario"); $estado = $consulta->execute(array(':idusuario' => $idusuario, ':nombre' => $datosform->post('nombre'), ':apellidos' => $datosform->post('apellidos'), ':email' => $datosform->post('email'))); // Si se han modificado datos... if ($consulta->rowCount() == 1) { echo json_encode(array('estado' => true, 'mensaje' => 'Datos actualizados correctamente.')); } else { echo json_encode(array('estado' => false, 'mensaje' => 'Error al actualizar datos, datos no modificados o registro no encontrado.')); } }); ////////////////////////////////////////////////////////////////////////////////////////////////// // A PARTIR DE AQUÍ ES UN EJEMPLO DE USO DE SLIM FRAMEWORK PARA CREAR UNA APLICACIÓN. ////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // // EJEMPLO DE USO DEL SLIM FRAMEWORK PARA GENERAR UNA APLICACIÓN. // //
$app->put('/events/:id', function ($id) use($app) { // get the base event data $old_event = Postmortem::get_event($id); if (is_null($old_event["id"])) { $app->response->status(500); return; } $event = ["title" => $old_event["title"], "id" => $id]; $params = $app->request->params(); foreach ($params as $key => $value) { switch ($key) { case "title": $event["title"] = $value; break; case "summary": $event["summary"] = $value; break; case "why_surprised": $event["why_surprised"] = $value; break; case "start_date": case "start_time": if (!isset($params["timezone"])) { $app->response->status(400); return; } $timezone = new DateTimeZone($params["timezone"]); $starttime = isset($event["starttime"]) ? $event["starttime"] : $old_event["starttime"]; $edate = new DateTime("@{$starttime}"); $edate->setTimezone($timezone); $new_date = date_parse($value); if ($key == "start_time") { $edate->setTime($new_date["hour"], $new_date["minute"]); } elseif ($key == "start_date") { $edate->setDate($new_date["year"], $new_date["month"], $new_date["day"]); } $event["starttime"] = $edate->getTimeStamp(); break; case "end_date": case "end_time": if (!isset($params["timezone"])) { $app->response->status(400); return; } $timezone = new DateTimeZone($params["timezone"]); $endtime = isset($event["endtime"]) ? $event["endtime"] : $old_event["endtime"]; $edate = new DateTime("@{$endtime}"); $edate->setTimezone($timezone); $new_date = date_parse($value); if ($key == "end_time") { $edate->setTime($new_date["hour"], $new_date["minute"]); } elseif ($key == "end_date") { $edate->setDate($new_date["year"], $new_date["month"], $new_date["day"]); } $event["endtime"] = $edate->getTimeStamp(); break; case "detect_date": case "detect_time": if (!isset($params["timezone"])) { $app->response->status(400); return; } $timezone = new DateTimeZone($params["timezone"]); $detecttime = isset($event["detecttime"]) ? $event["detecttime"] : $old_event["detecttime"]; $edate = new DateTime("@{$detecttime}"); $edate->setTimezone($timezone); $new_date = date_parse($value); if ($key == "detect_time") { $edate->setTime($new_date["hour"], $new_date["minute"]); } elseif ($key == "detect_date") { $edate->setDate($new_date["year"], $new_date["month"], $new_date["day"]); } $event["detecttime"] = $edate->getTimeStamp(); break; case "status_datetime": if (!$value) { $event["statustime"] = 0; break; } if (!isset($params["timezone"])) { $app->response->status(400); return; } $timezone = new DateTimeZone($params["timezone"]); $statustime = $old_event["statustime"]; $edate = new DateTime("@{$statustime}"); $edate->setTimezone($timezone); $new_date = date_parse($value); $edate->setTime($new_date["hour"], $new_date["minute"]); $edate->setDate($new_date["year"], $new_date["month"], $new_date["day"]); $event["statustime"] = $edate->getTimeStamp(); break; case "severity": $event["severity"] = $value; break; case "contact": $event["contact"] = $value; break; case "gcal": $event["gcal"] = $value; break; } } $event = Postmortem::save_event($event); if (is_null($event["id"])) { var_dump($event); $app->response->status(500); return; } $app->redirect('/events/' . $event["id"], 201); });
require_once '../../include/DbHandlers/UserDbHandler.php'; require_once '../../include/DbHandlers/MaterialDbHandler.php'; require '../../libs/Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); // User id from db - Global Variable $user_id = NULL; // --------------------------------------------------------------------- // ------ web services ------------------------------------------------- // --------------------------------------------------------------------- // Creating a new material in db $app->post('/materials', 'authenticate', 'createMaterials'); // Listing all materials $app->get('/materials', 'authenticate', 'getAllMaterials'); // Updating all materials included in payload $app->put('/materials', 'authenticate', 'updateMaterials'); // Deleting a set of materials $app->delete('/materials', 'authenticate', 'deleteMaterials'); // --------------------------------------------------------------------- // ------ Auxiliar methods --------------------------------------------- // --------------------------------------------------------------------- // Verifying required params posted or not function verifyRequiredParams($required_fields) { $error = false; $error_fields = ""; $request_params = array(); $request_params = $_REQUEST; // Handling PUT request params if ($_SERVER['REQUEST_METHOD'] == 'PUT') { $app = \Slim\Slim::getInstance();
$app->put('/:package/:name/:id', 'API', 'CHECKTOKEN', 'RATELIMITER', function ($package, $name, $id) use($r, $app) { $tableName = $r->genTableName($package, $name); if (!$r->packageOK($package, 'update') && $tableName !== 'managepackages') { return $r->respond(400, 'BAD REQUEST', true); } $request = json_decode($app->request()->getBody()); if (!is_array($request) && !is_object($request)) { return $r->respond(400, 'MALFORMED DATA', true); } $request = (array) $request; $data = R::findOne($tableName, 'id = ?', array($id)); if ($data) { $request = $r->fireHookIfExists($package, $name, 'beforeUpdate', $request, $data); if ($request === false) { return $r->respond(403, 'FORBIDDEN:HOOK', true); } $requestData = $r->serialize(array($request))[0]; foreach ($requestData as $key => $value) { $data->{$key} = $value; } R::store($data); $existingSyncMeta = R::findOne('syncmeta', 'where row_id = ? and tableName = ?', array($id, $tableName)); if ($existingSyncMeta) { $existingSyncMeta->type = 'update'; $existingSyncMeta->timestamp = date('Y-m-d H:i:s'); R::store($existingSyncMeta); } $data = $r->unserialize(array($data->export())); $data = array_shift($data); if ($data) { $r->fireHookIfExists($package, $name, 'afterUpdate', $data); return $r->respond(200, $data); } return $r->respond(500, 'ERROR WHILE INSERTING DATA', true); } return $r->respond(404, 'NOT FOUND', true); });
$request = $app->request(); if (!$dbHandler->checkAuth($request->params('key'))) { $app->response()->status(403); return; } $fields = isset($fields) ? explode(",", $fields) : null; $returnFields = $request->params('return'); $returnFields = $returnFields ? explode(",", $returnFields) : $fields; $app->response()->write($dbHandler->doInsert($fields, $table, $request->post(), $returnFields)); }); $app->put('/:table/:fields', function ($table, $fields) use($dbHandler, $app) { $request = $app->request(); if (!$dbHandler->checkAuth($request->params('key'))) { $app->response()->status(403); } else { $fields = isset($fields) ? explode(",", $fields) : null; $returnFields = $request->params('return'); $returnFields = $returnFields ? explode(",", $returnFields) : $fields; $where = $request->params('where'); $app->response()->write($dbHandler->doUpdate($fields, $table, $request->put(), $where, $returnFields)); } }); $app->post('/transaction', function () use($dbHandler, $app) { $request = $app->request(); if (!$dbHandler->checkAuth($request->params('key'))) { $app->response()->status(403); return; } $statements = json_decode($request->getBody(), true); $dbResult = $dbHandler->doTransaction($statements); if (!$dbResult) { $request->status(404);
$database->query($sql); $database->bind(':settings_desc', "apiKey"); $row = $database->single(); $user = $row['settings_value']; $passwd = $row['settings_extra']; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); // Authorization: Basic OXR1Y3VTTXUwSjpiTEc3NUJ2bVpM $app->add(new \Slim\Middleware\HttpBasicAuthentication(["users" => [$user => $passwd], "error" => function ($arguments) use($app) { $response["status"] = "error"; $response["message"] = $arguments["message"]; $app->response->write(json_encode($response, JSON_UNESCAPED_SLASHES)); }])); $app->get('/users', 'getUsers'); $app->get('/user/:user_id', 'getUsersId'); $app->put('/update/:user_id', 'updateUser'); $app->post('/insert', 'insertUser'); $app->delete('/delete/:user_id', 'deleteUser'); /* api Keys */ function validateKey($apiKey) { /* function hash_password($password, $salt) { $hash = hash_hmac("md5", $salt, $password); for ($i = 0; $i < 1000; $i++) { $hash = hash_hmac("md5", $hash, $password); } return $hash; } $database = new Database(); $sql="SELECT * FROM settings WHERE settings_desc=:settings_desc"; $database->query($sql);
$output = shell_exec('./statuscheck.sh all ' . $maxnum); echoResponse(200, $output); }); $app->put('/devices/', function () use($app) { $body = $app->request->getBody(); $params = json_decode($body); if (array_key_exists("deviceid", $params)) { if (array_key_exists("status", $params) && array_key_exists("level", $params)) { $output1 = shell_exec('./changestate.sh ' . $params->deviceid . ' ' . $params->status); $output2 = shell_exec('./changelevel.sh ' . $params->deviceid . ' ' . $params->level); echoResponse(200, '{' . $output1 . ',' . $output2 . '}'); } else { if (array_key_exists("status", $params)) { $output = shell_exec('./changestate.sh ' . $params->deviceid . ' ' . $params->status); echoResponse(200, '{' . $output . '}'); } else { if (array_key_exists("level", $params)) { $output = shell_exec('./changelevel.sh ' . $params->deviceid . ' ' . $params->level); echoResponse(200, '{' . $output . '}'); } else { echoResponse(200, '{"Response":"Must include a status or level"}'); } } } } else { echoResponse(200, '{"Response":"Must include a deviceid"}'); } }); $app->get('/', function () use($app) { echoResponse(200, '{"Error":"Must include the deviceid"}'); });
<?php require 'vendor/autoload.php'; require_once 'lib/Slim/Controller/API/Person.php'; require_once 'lib/Slim/Controller/API/Job.php'; require_once 'lib/Slim/Controller/API/Alexa.php'; if (!file_exists('config.json')) { die("Missing configuration file config.json"); } $application_settings = json_decode(file_get_contents('config.json'), TRUE); if (is_null($application_settings)) { die("config file exist but was not able to be decoded. Bad JSON?"); } $app = new \Slim\Slim($application_settings); $app->config('job_dir', __DIR__ . '/jobs/'); $app->get('/api/person/', '\\Slim\\Controller\\API\\Person:getAllPeople'); $app->get('/api/person/:username', '\\Slim\\Controller\\API\\Person:getPerson'); // This should be a patch put this is not implemented in the version of lighttpd I am current running :( $app->put('/api/person/:username', '\\Slim\\Controller\\API\\Person:patchPerson'); $app->post('/api/person/:username/action/:action/location/:location', '\\Slim\\Controller\\API\\Person:changeLocationForPerson'); // Run a job directly @TODO might need to do something so that jobs do not get executed automatically here $app->post('/api/job/:job/', '\\Slim\\Controller\\API\\Job:executeJob')->name('execute_job'); $app->get('/api/job/:job/', '\\Slim\\Controller\\API\\Job:executeJob')->name('execute_job'); $app->post('/api/alexa/:skill/', '\\Slim\\Controller\\API\\Alexa:handleRequest'); $app->run();
response(200, $response); } else { $response['error'] = true; $response['mensagem'] = 'Não existem categorias a serem apresentadas!'; response(200, $response); $app->stop(); } }); $app->put('/cadastrar/categoria', function () use($app, $db) { $data = json_decode($app->request->getBody()); $nome = $data->nome; $usuario = $data->usuario; $res = $db->query(sprintf("INSERT INTO ctg (ctg_nm,usr_usr_id) VALUE ('%s','%s')", $nome, $usuario)); if ($res) { $response['error'] = false; $response['mesnsagem'] = 'Categoria cadastrada com sucesso.'; response(200, $response); } else { $response['error'] = true; $response['mensagem'] = 'Erro ao cadastrar categoria.'; response(200, $response); $app->stop(); } }); $app->put('/alterar/categoria', function () use($app, $db) { $data = json_decode($app->request->getBody()); $id = $data->id; $nome = $data->nome; $usuario = $data->usuario; $res = $db->query(sprintf("UPDATE ctg SET ctg_nm = '%s' WHERE ctg_id = '%s' AND usr_usr_id = '%s'", $nome, $id, $usuario)); if ($res) { $response['error'] = false;
$app->configureMode('development', function () use($app) { $app->config(array('debug' => true, 'log.enable' => true, 'log.level' => \Slim\Log::DEBUG)); }); $app->configureMode('production', function () use($app) { $app->config(array('debug' => false, 'log.enable' => true, 'log.level' => \Slim\Log::DEBUG)); }); $app->group('/users', function () use($app) { global $decode_body; $app->post('', $decode_body, function () { create_user(); }); $app->group('/:username', function () use($app) { global $check_token_exists; global $decode_body; $app->put('', $check_token_exists, $decode_body, function ($username) { change_pwd($username); }); $app->delete('', $check_token_exists, function ($username) { delete_user($username); }); }); }); $app->group('/calendars', function () use($app) { global $check_token_exists; global $decode_body; $app->get('', $check_token_exists, function () { get_calendars(); }); $app->post('', $check_token_exists, $decode_body, function () { create_calendar(); });
* Updating existing contact * method PUT * params contact, status * url - /contacts/:id */ $app->put('/contacts/:id', 'authenticate', function ($contact_id) use($app) { // check for required params verifyRequiredParams(array('contact', 'status')); global $user_id; $contact = $app->request->put('contact'); $status = $app->request->put('status'); $db = new DbHandler(); $response = array(); // updating task $result = $db->updateTask($user_id, $contact_id, $contact, $status); if ($result) { // contact updated successfully $response["error"] = false; $response["message"] = "Contact updated successfully"; } else { // contact failed to update $response["error"] = true; $response["message"] = "Contact failed to update. Please try again!"; } echoRespnse(200, $response); }); /** * Deleting contact. Users can delete only their contacts * method DELETE * url /tasks */
chdir(__DIR__ . '/../../../'); ini_set('session.use_cookies', 0); require 'vendor/autoload.php'; \Caco\MiniAR::setDefaultPdo($pdo = new \PDO('sqlite:database/app.sqlite3')); $pdo->exec('PRAGMA foreign_keys = ON'); $app = new \Slim\Slim(); $app->view(new \Caco\Slim\JsonView()); $app->add($auth = new \Caco\Slim\Auth\Basic()); $auth->setRealm('Caco Cloud'); $app->group('/password', function () use($app) { $app->get('/:key/:id', '\\Caco\\Password\\REST:one')->conditions(['id' => '\\d+']); $app->get('/:key', '\\Caco\\Password\\REST:all'); $app->post('/:key', '\\Caco\\Password\\REST:add'); $app->delete('/:key/:id', '\\Caco\\Password\\REST:delete')->conditions(['id' => '\\d+']); $app->put('/:key/:id', '\\Caco\\Password\\REST:edit')->conditions(['id' => '\\d+']); }); $app->group('/bookmark', function () use($app) { $app->get('/:id', '\\Caco\\Bookmark\\REST:one')->conditions(['id' => '\\d+']); $app->get('', '\\Caco\\Bookmark\\REST:all'); $app->post('', '\\Caco\\Bookmark\\REST:add'); $app->delete('/:id', '\\Caco\\Bookmark\\REST:delete')->conditions(['id' => '\\d+']); $app->put('/:id', '\\Caco\\Bookmark\\REST:edit')->conditions(['id' => '\\d+']); }); $app->group('/config', function () use($app) { $app->get('/:key', '\\Caco\\Config\\REST:one'); $app->get('', '\\Caco\\Config\\REST:all'); $app->post('', '\\Caco\\Config\\REST:add'); $app->delete('/:key', '\\Caco\\Config\\REST:delete'); $app->put('/:key', '\\Caco\\Config\\REST:edit'); });
// Band-Controller instanziieren $ctrlCD = new CDController(); echo json_encode($_REQUEST, JSON_NUMERIC_CHECK); // echo json_encode(array('type' => $_REQUEST['type'], 'id' => $_REQUEST['id']), JSON_NUMERIC_CHECK); // CD-Info aus Datenbank holen // Mögliche Typen ($_REQUEST['type']): // - songs // - ... // $ctrlCD->PostCdInfo((object) array( // 'type' => $_REQUEST['type'], // 'id' => $_REQUEST['id'] // )); }); // $app->put('/cd/:id', function ($id) use ($db, $app) { $app->put('/cd/:id', function ($id) use($app) { // update data }); $app->delete('/cd/:id', function ($id) use($db) { // delete data }); // --- Bands ---- /** * (GET) * Liefert ein Array mit Band-Objekten aller Bands zurück */ $app->get('/bands', function () use($app) { // // Band-Controller instanziieren $ctrlBand = new BandController(); // // Alle Bands aus Datenbank holen $ctrlBand->GetBand(); });
$user = User::getUser($userId); }); $app->get('/getAllUser', function () { //renvoi toutes les infos de tous les utilisateurs $user = User::getAllUser(); }); $app->post('/AddUser', function () { //ajoute un utilisateur $user = User::AddUser($_POST["pseudo"], $_POST["email"], $_POST["password"], $_POST["birthdate"], $_POST["city"], $_POST["budget"]); }); $app->get('/connexion/:pseudo/:password', function ($pseudo, $password) { User::connexion($pseudo, $password); //retourne userID si ok sinon retourne 0 }); $app->put('/modifUser', function () { //modifier utilisateur $user = User::UpdateUser($_POST["pseudo"], $_POST["email"], $_POST["password"], $_POST["birthdate"], $_POST["city"], $_POST["budget"], $_POST["id"]); }); $app->delete('/delUser', function () { //modifier utilisateur $user = User::DeleteUser($_POST["id"]); }); /*-------------------------------------------------- FRIGO --------------------------------------------------*/ $app->get('/getIngredientsFridge/:userId', function ($userId) { Frigo::getIngredientsFridge($userId); //renvoi tous les ingrédients du frigo de l'utilisateur }); $app->get('/getIngredientsFridgeWithFiltre/:userId/:filtre/:donnee', function ($userId, $filtre, $donnee) { Frigo::getIngredientsFridgeWithFiltre($userId, $filtre, $donnee); //renvoi tous les ingrédients du frigo de l'utilisateur avec filtre
$r = array(); foreach ($ke as $k) { $r[] = $k->getSerial(); } echo json_encode($r); }); $app->get('/kategorija/:id/', function ($id) use($twig, $em, $urls, $app) { $k = $id == 'root' ? $em->getRepository('Kategorija')->findOneBy(array('naziv' => 'root')) : $em->find('Kategorija', $id); echo json_encode($k->getSerial()); }); $app->post('/kategorija/', $login('admin'), function () use($app, $em) { $k = new Kategorija(); if (param_set_value($k, 'naziv')) { param_set_entity('Kategorija', $k, 'parent'); param_set_value($k, 'prioritet'); $em->persist($k); $em->flush(); $app->stop(); } $app->halt(400, 'Nisu dostavljeni svi neophodni parametri u zahtjevu. [naziv]'); }); $app->put('/kategorija/:id/', $login('admin'), function ($id) use($em) { }); $app->delete('/kategorija/:id/', $login('admin'), function ($id) use($em) { }); // ** SESIJA ** $app->get('/sesija/', $login, function () use($twig, $em, $urls, $app) { $env = $app->environment(); echo json_encode($env['ulogovan']['korisnik']->getSerial()); }); $app->run();
$sql = "insert into guestbook (email,comment,created) values ('{$email}','{$comment}',Now())"; if ($connection->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $connection->error; } } else { echo 'Error in variables'; } }); // PUT route $app->put('/hello/:id', function () { $server = 'localhost'; // this may be an IP address instead $user = '******'; $pass = ''; $database = 'guestbook'; $connection = new mysqli($server, $user, $pass, $database); 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 *
$app->render(200, $result); } else { $app->render(404, array('error' => true, 'msg' => 'Link has not been found')); } })->conditions(array('id' => '\\d+')); $app->put('/addLink', function () use($app) { $putData = $app->request->put(); if (array_key_exists('url', $putData)) { $url = $putData['url']; if ($app->api->validateUrl($url)) { if (strpos($url, $app->domain)) { $app->render(200, array('msg' => 'Huehue, nice try! <img src="http://' . $app->domain . '/media/gfx/smtlikethis.jpg" alt="">', 'zonk' => true)); return; } $existingUrl = $app->api->getLinkByUrl($url); if ($existingUrl) { $app->render(200, $existingUrl); } else { $lastInsertId = $app->api->addLink($url); $result = $app->api->getLinkById($lastInsertId); $app->render(201, $result); } } else { $app->render(400, array('error' => true, 'msg' => 'Provided url is not in a valid form')); } } else { $app->render(400, array('error' => true, 'msg' => 'Parameter `url` must be set')); } }); }); $app->run();
*/ $app->put('/journey/:id', 'authenticate', function ($journey_id) use($app) { // check for required params //verifyRequiredParams(array('status')); global $user_id; // Admin is user 1. Special privedges // but cant change journey status if ($user_id == 1) { $response["error"] = false; $response["message"] = "Admin can only view journeys"; echoRespnse(400, $response); $app->stop(); } $status = 1; //$app->request->put('status'); $db = new DbHandler(); $response = array(); // updating journey $result = $db->updateJourney($user_id, $journey_id, $status); if ($result) { // journey updated successfully $response["error"] = false; $response["message"] = "Journey status updated successfully"; } else { // journey failed to update $response["error"] = true; $response["message"] = "Journey status failed to update. Please try again!"; } echoRespnse(200, $response); }); /*
<?php require dirname(__DIR__) . '/vendor/autoload.php'; $app = new Slim\Slim(); $view = new Pug\Example\Simple($app); // Request전체를 보고자 할때. $app->get("/status", [$view, 'showStatus']); $app->post("/status", [$view, 'showStatus']); $app->put("/status", [$view, 'showStatus']); $app->delete("/status", [$view, 'showStatus']); // 일반적인 상황의 로그인과 로그아웃 $app->post('/login', [$view, 'normalLogin']); $app->get('/me', [$view, 'normalMe']); // 크로스 도메인의 경우 로그인과 로그아웃 (세션 분리) $app->post('/cors/login', [$view, 'corsLogin']); $app->get('/cors/me', [$view, 'corsMe']); $app->run();
$boolString = $add ? 'true' : 'false'; echo $boolString; }); //Display All Users: $app->get('/user/', function () { global $user, $app; echo json_encode($user->getAllUsers()); //var_dump ($user->getAllUsers()); }); //Display specific user $app->get('/user/:id', function ($id) { global $user, $app; $user = $user->getUser($id); echo $user[0]['user_email']; //echo ( json_encode($user->getUser($id)) ); }); //Delete User $app->delete('/user/:id', function ($id) { global $user, $app; $user->deleteUser($id); }); //Update User $app->put('/user/:id', function ($id) { global $user, $app; //var_dump($app->request->getBody()); $jsonUser = json_decode($app->request->getBody(), true); var_dump($jsonUser); $user->updateUser($jsonUser); }); // $app->run();
require_once '../service/ContraMedidaService.php'; require_once '../model/ContraMedida.php'; require_once '../Slim/Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); $contraMedidaService = new ContraMedidaService(); $app->get("/", function () { echo "<h1>Hello World</h1>"; }); $app->get("/contraMedida/getall", function () use($app, $contraMedidaService) { echo '{"contraMedidas": ' . json_encode($contraMedidaService->buscarContraMedidas()) . '}'; }); $app->get("/contraMedida/:id", function ($id) use($app, $contraMedidaService) { echo json_encode($contraMedidaService->buscarContraMedida($id)); }); $app->post("/contraMedida/cadastrar", function () use($app, $contraMedidaService) { $app->response()->header("Content-Type", "application/json"); $resultado = json_decode($app->request()->getBody()); echo json_encode($contraMedidaService->cadastrarContraMedida($resultado->nomeContraMedida)); }); $app->put("/contraMedida/atualizar", function ($id) use($app, $contraMedidaService) { $app->response()->header("Content-Type", "application/json"); $resultado = json_decode($app->request()->getBody()); echo json_encode($contraMedidaService->atualizarContraMedida($resultado->idContraMedida, $resultado->nomeContramedida)); }); $app->delete("/contraMedida/remover/:id", function ($id) use($app, $contraMedidaService) { $app->response()->header("Content-Type", "application/json"); $resultado = json_decode($app->request()->getBody()); echo json_encode($contraMedidaService->removerContraMedida($id)); }); $app->run();
<?php require '../libs/Slim/Slim.php'; require 'dbConnect.php'; require 'listsFunctions.php'; require 'itemsFunctions.php'; require 'helperFunctions.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); $app->contentType('application/json'); //PROJECTS $app->get('/projects', 'getProjects'); $app->get('/project/:id', 'getProject'); $app->post('/projects', 'addProject'); $app->put('/project/:id', 'updateProject'); $app->delete('/project/:id', 'deleteProject'); //RUNNERS $app->get('/runners/adults', 'getAllAdultRunners'); $app->get('/runners/halfmarathon', 'getSmRunners'); $app->get('/runners/cross', 'getCrossRunners'); $app->get('/runners/relay4', 'getRelay4Runners'); $app->get('/runners/relay2', 'getRelay2Runners'); $app->get('/runners/companies', 'getCompaniesRunners'); $app->get('/runners/children', 'getChildrenRunners'); $app->get('/runners/all', 'getAllRunners'); $app->get('/runner/:id', 'getRunner'); $app->post('/runners/adults', 'addRunner'); $app->post('/runners/relay2', 'addListOfRunners'); $app->post('/runners/relay4', 'addListOfRunners'); $app->post('/runners/company', 'addListOfRunners'); $app->post('/runners/children', 'addRunner');
if (!$fp) { exit("Couldn't open file\n "); } fwrite($fp, $allPostVars); fclose($fp); echo "Posted \n"; echo $data; }); // END POST $app->get('/get', function () { $mydata = file_get_contents("test.json"); print $mydata; }); // 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'; }); /* My APIs */ $app->get('/hello/:name', function ($name) { echo "Hello, " . $name; }); $app->get('/fslist/:foldername', function ($foldername) { $targetpath = "../{$foldername}";
$response = array('status' => 'false', 'message' => "Email already exists"); } $app->response()->header('Content-Type', 'application/json'); echo json_encode($response); //echo json_encode($array); }); //Put method to update the data into database $app->put('/houses/:id', function ($id = null) use($app, $db) { $houses = $db->houses()->where('id', $id); $app->response()->header('Content-Type', 'application/json'); $data = null; if ($houses->fetch()) { /* * We are reading JSON object received in HTTP request body and converting it to array */ $post = $app->request()->put(); $info = array("house_rent_amount" => $post['house_rent_amount']); /* * Updating Person */ $data = $houses->update($info); } echo json_encode(array("status" => (bool) $post, "message" => "data updated successfully")); }); $app->put('/updatehouses/:id', function ($id = null) use($app, $db) { $houses = $db->houses()->where('id', $id); $app->response()->header('Content-Type', 'application/json'); $data = null; if ($houses->fetch()) { /* * We are reading JSON object received in HTTP request body and converting it to array
$datos = json_decode($request, true); // guardamos el archivo subido move_uploaded_file($datos, "img/archivo.png"); echo json_encode($datos); }); /* * Ruta para actualizar un producto desde el panel de administración */ $app->put('/producto', function () use($app) { // conectar con la BD y seleccionar la colección $mongo = new MongoClient(); $database = $mongo->plazamar; $collection = $database->productos; // recuperar los datos enviados por backbone $request = $app->request()->getBody(); $datos = json_decode($request, true); $nuevosDatos = ['titulo' => $datos['titulo'], 'autor' => $datos['autor'], 'editorial' => $datos['editorial'], 'precio' => $datos['precio'], 'isbn' => $datos['isbn'], 'categoria' => $datos['categoria'], 'tieneDescuento' => $datos['tieneDescuento'], 'descuento' => $datos['descuento'], 'imagen' => $datos['imagen']]; // establecemos la clave de búsqueda en la BD $claveBusqueda = ['_id' => new MongoID($datos['id'])]; // grabar los datos en mongodb $collection->update($claveBusqueda, $nuevosDatos); echo json_encode($datos); }); /* * Ruta para borrar un producto de la base de datos desde el panel de administración */ $app->delete('/producto', function () use($app) { // recoger la query string de la url pasada por backbone $req = $app->request(); $id = $req->get('identificador'); // conectar con la BD y seleccionar la colección
$app->group('/devices', function () use($app) { $app->delete('/:hostname', 'authToken', 'del_device')->name('del_device'); // api/v0/devices/$hostname $app->get('/:hostname', 'authToken', 'get_device')->name('get_device'); // api/v0/devices/$hostname $app->patch('/:hostname', 'authToken', 'update_device')->name('update_device_field'); $app->get('/:hostname/vlans', 'authToken', 'get_vlans')->name('get_vlans'); // api/v0/devices/$hostname/vlans $app->get('/:hostname/graphs', 'authToken', 'get_graphs')->name('get_graphs'); // api/v0/devices/$hostname/graphs $app->get('/:hostname/ports', 'authToken', 'get_port_graphs')->name('get_port_graphs'); $app->get('/:hostname/port_stack', 'authToken', 'get_port_stack')->name('get_port_stack'); // api/v0/devices/$hostname/ports $app->get('/:hostname/components', 'authToken', 'get_components')->name('get_components'); $app->post('/:hostname/components/:type', 'authToken', 'add_components')->name('add_components'); $app->put('/:hostname/components', 'authToken', 'edit_components')->name('edit_components'); $app->delete('/:hostname/components/:component', 'authToken', 'delete_components')->name('delete_components'); $app->get('/:hostname/groups', 'authToken', 'get_device_groups')->name('get_device_groups'); $app->get('/:hostname/:type', 'authToken', 'get_graph_generic_by_hostname')->name('get_graph_generic_by_hostname'); // api/v0/devices/$hostname/$type $app->get('/:hostname/ports/:ifname', 'authToken', 'get_port_stats_by_port_hostname')->name('get_port_stats_by_port_hostname'); // api/v0/devices/$hostname/ports/$ifName $app->get('/:hostname/ports/:ifname/:type', 'authToken', 'get_graph_by_port_hostname')->name('get_graph_by_port_hostname'); // api/v0/devices/$hostname/ports/$ifName/$type }); $app->get('/devices', 'authToken', 'list_devices')->name('list_devices'); // api/v0/devices $app->post('/devices', 'authToken', 'add_device')->name('add_device'); // api/v0/devices (json data needs to be passed) $app->group('/devicegroups', function () use($app) { $app->get('/:name', 'authToken', 'get_devices_by_group')->name('get_devices_by_group');