-2

I'm developing a web RESTful API using slim framework of php.I want to know how do I add some annotation type thing on POST method so that it can behave as URL encoded method.Please help me in this regard.Advance thanks.

Asad Yasin
  • 93
  • 10

2 Answers2

1

There is no pre-programmed way for this - there is no Slim or php method that will definitively check if your string is urlencoded. What you can do is implement Slim Middleware to your route.

<?php
$app = new \Slim\App();

$mw = function ($request, $response, $next) {
    if ( urlencode(urldecode($data)) === $data){
      $response = $next($request, $response);
    } else {
      $response = ... // throw error
    }

    return $response;
};

$app->get('/', function ($request, $response, $args) { // Your route
    $response->getBody()->write(' Hello ');

    return $response;
})->add($mw); // chained middleware

$app->run();

Discussion: Test if string is URL encoded in PHP

Middleware: https://www.slimframework.com/docs/v3/concepts/middleware.html

domagoj
  • 906
  • 1
  • 8
  • 20
0

Since you're using Slim as the foundation to your API, the easiest way is to just build a GET route with the desired URL parameters defined:

$app->get('/users/filter/{param1}/{param2}/{param3}', function (Request $request, Response $response) {
    // Route actions here
});

In your documentation, make sure you inform the consumers of this API that it is a GET endpoint, so that a POST body should not be made; rather, the parameters that you outline in the URL should be used to pass the client's data over to the API.

If you are intent on using a POST route with just URL parameters, then you could also force a response back if the route detects an incoming POST body:

$app->post('/users/filter/{param1}/{param2}/{param3}', function (Request $request, Response $response) {

    $postBody = $request->getParsedBody();

    if (is_array($postBody)) {

        $denyMsg = "This endpoint does not accept POST body as a means to transmit data; please refer to the API documentation for proper usage.";
        $denyResponse = $response->withJson($denyMsg, $status = null, $encodingOptions = 0);

        return $profileData;

    }
});
prafferty
  • 101
  • 8