Based on yiisoft/yii2-app-advanced, create a new repository yii2-app-advanced on github, and create a new interface application (implement RESTful-style web service services. API), application/x-www-form-urlencoded and multipart/form-data input formats, default support, new application/json input format support
1. The API can distinguish application/x-www-form-urlencoded and multipart/form-data input formats by default, and view \api\config\main.php, request Configuration of application components
'request' => [
'csrfParam' => '_csrf-api',
],
2. POST request in Postman,http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/users, the input format: application/x-www-form-urlencoded, as shown in Figure 1
3. Post request in Postman,http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/users, input format: multipart/form-data, as shown in Figure 2
4. Post request in Postman,http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/users, the input format: application/json, data verification failed, as shown in Figure 3
{
"code": 20004,
"message": "数据验证失败:Username不能为空。"
}
5. Configure the request application component[[yii\web\Request::$parsers|parsers]] attribute uses[[yii\web\JsonParser]] for JSON input, this property is used to convert the original HTTP request body to $BodyParams
'request' => [
'csrfParam' => '_csrf-api',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],
6. Post request in Postman,http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/users, input format: application/x-www-form-urlencoded
{
"code": 10000,
"message": "创建用户成功",
"data": {
"username": "444444",
"email": "444444@163.com",
"password_hash": "$2y$13$qXQwOfXLzPykyk/ymI3z3ua2WofRkrJT5NcmeiyUx8Iko51YdMeg.",
"auth_key": "H8BmGgHLZRGd_1vvU8ESXrAi1pyaL-59",
"status": 1,
"created_at": 1532409559,
"updated_at": 1532409559,
"id": 19
}
}
7. Post request in Postman,http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/users, input format: multipart/form-data
{
"code": 10000,
"message": "创建用户成功",
"data": {
"username": "555555",
"email": "555555@163.com",
"password_hash": "$2y$13$9NByl.XSlo/rzzmmUZWZT.k6Ncpk.br9py1PywpyXRjThsjEQaAMK",
"auth_key": "tQuKPECDLAAqpjDc44CpCK7ynypuLbJ-",
"status": 1,
"created_at": 1532409634,
"updated_at": 1532409634,
"id": 20
}
}
8. Post request in Postman,http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/users, input format: application/json, as shown in Figure 4
{
"code": 10000,
"message": "创建用户成功",
"data": {
"username": "666666",
"email": "666666@163.com",
"password_hash": "$2y$13$SmCEU6tS2qpwU3ggbAkWce5wMZP5BWtqkAgCd.vxbyjN3TwsX32d.",
"auth_key": "D2aVPy___U-aySPYR-1-Y6msxipJulqE",
"status": 1,
"created_at": 1532409697,
"updated_at": 1532409697,
"id": 21
}
}



