I'm working on a Rest API with SLIM FRAMEWORK 3, and I need to check if a GET call returns a specific data in Middleware. If no data is returned, I need to make a new call with the POST method first to write the data in the API, and then to continue with $next().
I tried the withRedirect(), but it seems to only work with GET. Is there any way to do this? Thanks.
<?php
$app->add(function($req, $res, $next){
$uri = $req->getUri()->getPath();
//get query_string params
$params = $req->getUri()->getQuery();
parse_str($params, $args);
//check if is desired route...
if($req->isGet() && isset($args['name']) && isset($args['borndate']) && $uri == 'api/v1/example'){
global $app;
//try to get data from DB
$dados_mapa = (new App\Models\MyExampleModel())->get()
->where('name', '=', $args['name'])
->where('borndate', '=', $args['borndate'])
->first();
//check data
if(isset($dados_mapa->id))
{
//data exists, continue
return $next($req, $res);
}else{
//no data, I need to do a POST call here...
$new_post_uri = 'api/v1/example';
doPostHere($new_post_uri); ////how to make this POST?
//continue with the first call
return $next($req, $res);
}
}
});
To answer your question, use Guzzle
to do a POST request as you want to do a new HTTP call and Guzzle is quite a good HTTP client for PHP.
However, be aware that this is a particularly poor pattern to use and you should not do this. A GET should not have side-effects and creating new data is certainly a side-effect!
A better pattern would be to return a 4xx error if the data doesn't exist and then get the client to do the POST request to create it.