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

  1. To convert (parse) all type of Request data in a single format (like array, json, xml  format).
  2. 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:

  • Configuring URL Rules

After it, modify the configuration of the urlManager component in your application configuration like this :

 

  • 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.

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.

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 :  

 

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.

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 :

  1. FORMAT_JSON : The “Content-Type” header will set as “application/json”.
  2. FORMAT_XML : The “Content-Type” header will set as “application/xml”.
  3. FORMAT_RAW : No extra HTTP header will be added.
  4. FORMAT_HTML : The “Content-Type” header will set as “text/html”.
  5. FORMAT_JSONP : The “Content-Type” header will set as “text/javascript”.

Comments