Last active
September 2, 2020 10:33
-
-
Save pixelbrackets/3f46285c027eae6026d04bd6d137d351 to your computer and use it in GitHub Desktop.
slim-example-api
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require __DIR__ . '/../vendor/autoload.php'; | |
/** | |
* Slim: https://packagist.org/packages/slim/slim | |
* Slim PSR7 implementation https://packagist.org/packages/slim/psr7 | |
* Slim PSR-7 object decorators https://packagist.org/packages/slim/http | |
* | |
* Examples calls: | |
* http 127.0.0.1:8080/ # GET homepage | |
* http 127.0.0.1:8080/build/ token=foo # POST JSON Build endpoint | |
**/ | |
use Psr\Http\Message\ResponseInterface as Response; | |
use Psr\Http\Message\ServerRequestInterface as Request; | |
use Slim\Factory\AppFactory; | |
$app = AppFactory::create(); | |
// homepage | |
$app->get('/', function (Request $request, Response $response) { | |
$response->getBody()->write('Endpoints: <ul><li>/build</li></ul>'); | |
return $response; | |
}); | |
// build endpoint | |
$app->post('/build/', function (Request $request, Response $response) { | |
/* | |
// Without slim/http package -> plain PSR-7 response modification | |
$data = $request->getBody(); | |
$response->getBody()->write(json_encode([ | |
'success' => true, | |
'token' => $data['token'] | |
])); | |
return $response | |
->withHeader('Content-Type', 'application/json'); | |
*/ | |
$data = $request->getParsedBody(); | |
return $response->withJson([ | |
'success' => true, | |
'token' => $data['token'] | |
]); | |
}); | |
$app->run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: This requires redirecting all request to index.php → https://gist.github.com/pixelbrackets/8ba866dcb207b461f0ed0bc5af45927b