How to parse Request/ Response in Rest Api’s in yii2
- Digital Engineering
- General
How to parse Request/ Response in Rest Api’s in yii2
Yii provides a whole set of tools to simplify the implementation of Restful Web Service APIs. In particular, It is all about converting request and response parameters in Apis.
Goals
- To convert (parse) all type of Request data in a single format (like array, json, xml format).
- To convert (parse) all type of Response data into a single format (like array, json, xml format).
NOTE : Here all types means XML, JSON and MultiPart Form Data. Basically we play with these formats only in rest apis.
Specifications
Yii2 has the Built-in Libraries to parse the request data. There are some ways to parse data in yii2 as following –
1. Enabling Request Input :
First of all, create a controller in your rest api directory and then modify some configurations for url manager, then enable the parser for input. For Eg :
-
Creating a Rest-Controller
First, create a controller class frontend\modules\v1\controllers\DepartmentController as follows:
1 2 3 4 5 6 7 8 |
namespace frontend\modules\v1\controllers; use yii\rest\ActiveController; class DepartmentController extends ActiveController { public $modelClass = 'frontend\modules\v1\models\Department; } |
-
Configuring URL Rules
After it, modify the configuration of the urlManager component in your application configuration like this :
1 2 3 4 5 6 7 8 |
'urlManager' => [ 'enablePrettyUrl' => true, 'enableStrictParsing' => true, 'showScriptName' => false, 'rules' => [ ['class' => 'yii\rest\UrlRule', 'controller' => 'api\master'], ], ] |
-
Enable the Parser (JSON):
In request object of config file, add a parser setting to let the API accept input data in JSON format, . Here yii\web\JsonParser is built-in class in yii2 directory.
1 2 3 4 5 |
'request' => [ 'parsers' => [ 'application/json' => 'yii\web\JsonParser', ] ] |
NOTE : Without the above configuration, the API would only recognize application/x-www-form-urlencoded and multipart/form-data input formats.
OR
-
Enable the Parser (XML):
Since most modern applications and APIs don’t support XML instead, So it’s often necessary to convert XML Formatted Data.
1 2 3 4 5 |
'request' => [ 'parsers' => [ 'application/xml => 'yii\web\XmlParser', ] ] |
NOTE : yii2 doesn’t support yii\web\XmlParser directly, so it will managed dynamically by creating its library.
Creating dynamic library named yii\web\XmlParser :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<?php namespace yii\web; use yii\base\InvalidParamException; class XmlParser implements RequestParserInterface { public $asArray = true; public $throwException = true; /** * Parses a HTTP request body. * @param string $rawBody the raw HTTP request body. * @param string $contentType the content type specified for the request body. * @return array parameters parsed from the request body * @throws BadRequestHttpException if the body contains invalid xml and [[throwException]] is `true`. */ public function parse($rawBody, $contentType) { try { $parameters = simplexml_load_string($rawBody); if($this->asArray) { $parameters = (array) $parameters; } return $parameters === null ? [] : $parameters; } catch (InvalidParamException $e) { if ($this->throwException) { throw new BadRequestHttpException('Invalid XML data in request body: ' . $e->getMessage()); } return []; } } } |
NOTE : After adding request parser, all request input will be inside Yii::$app->request->post();
2. Enabling Response Input :
\yii\web\Response class represents an HTTP response. Response is configured as an application component in yii\web\Application by default.
1 2 3 |
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_XML; |
We can set it in the controller’s action somewhere before return. After adding this all data will convert in selected format as response.
All response formats are as follows :
- FORMAT_JSON : The “Content-Type” header will set as “application/json”.
- FORMAT_XML : The “Content-Type” header will set as “application/xml”.
- FORMAT_RAW : No extra HTTP header will be added.
- FORMAT_HTML : The “Content-Type” header will set as “text/html”.
- FORMAT_JSONP : The “Content-Type” header will set as “text/javascript”.
Related content
Auriga: Leveling Up for Enterprise Growth!
Auriga’s journey began in 2010 crafting products for India’s