Support for both POST and JSON formatted requests in slim 2

I support the backend APIwritten in slim 2. api is mainly used by mobile applications, so I want to switch from sending requests in the form of POST data to sending formatted strings JSON. This will simplify the api, since applications that currently send arrays, and even json strings as post-data variables.

As long as a simple update of mobile applications and transition to json-formatted requests POST, the backend api will have to support both formats for some time, until all users update their applications.

I am looking for a replacement function $app->request->post()that either gets the request parameter from mail data or from json data, depending on the type of content that was sent by the client.

For example, im uses $app->request->post('user_id', 0);to get a variable from post data.

I got installed in my api and it will convert json body to array. the problem is that now each of my api functions needs to check the array $app->json_bodyor $app->request->postto get request parameters.

For example:

$app->get('/settings', function () use($app, $freeze)
{
   if ($app->json_body != null) {
      $user_id = $app->json_body['user_id'];
   } else {
      $user_id = $app->request->post('user_id', 0);
   }
}

It is quite difficult to create a global function that does this, but I am looking for this function for a thin instance $app.

+4
source share
1 answer

https://github.com/slimphp/Slim-Middleware , JSON Content-Type: application/json.

+1

Source: https://habr.com/ru/post/1612917/


All Articles