且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么要为 RESTful API 创建一个单独的应用程序?

更新时间:2023-11-30 13:08:10

这意味着你必须创建一个像前端或后端这样的应用程序(Yii 2 高级应用程序模板),您需要做的是创建另一个与后端或前端相同的目录调用api",它将包含与后端|前端相同的文件夹结构,但资产、视图、小部件等除外.

It means you have to create an application like frontend or backend(Yii 2 advanced application template), what you have to do is create another directory call 'api' same as backend or frontend, and it'll contain folder structure same as backend|frontend except assets, views, widgets etc.

基本上你需要这样的文件夹结构

Basically you need folder structure like this

api

-config
-modules
--v1
---controllers
---models
-runtime
-tests
-web

backend
common
console
environments
frontend

如果您打算使用Yii 2 基本应用模板来开发rest api,这是可能的.创建模块调用 'api' 并创建一个子目录调用 'v1' 作为子模块.(Yii doc -A 模块可能包含子模块.)(GiovanniDerks - 后端子模块)


If you'r going to use Yii 2 basic application template to develop rest api, it's posible. create module call 'api' and create a sub directory call 'v1' as sub-module. (Yii doc -A module may consist of sub-modules.)(GiovanniDerks - backend sub-modules)

-modules
--api
---v1
----controllers
----models

使用这些文件夹结构之一有一个优势,因为您不必担心路由.

There is an advantage of using one of these folder structure, because you don't have to worry about route much.

https://domain.com/api/v1/products

这是带有高级模板的 RESTful API 的好例子

Here is good example for RESTful API with advance template

在 Yii2(budiirawan) 中设置 RESTful API

API &RESTFull API 是不同的.RESTFull API 必须具有 REST 标准.基本上这就是 API 被开发为单独应用程序的原因.在普通应用中,我们为 CRUD 函数创建了 4 个动作.但是在 yii2 RESTFull API 中,我们只为所有 CRUD 函数创建一个操作.(控制器从 REST 活动控制器扩展 - yii\rest\ActiveController ).在核心代码中,您可以找到针对不同标头 GET、POST、PUT & 的 4 个操作.删除.

API & RESTFull API are different. RESTFull APIs have to have REST standards. basically that's why APIs are developed as separate application. in normal app, we create 4 actions for CRUD functions. but in yii2 RESTFull API we just create One action for all CRUD functions. (Controllers extend from REST Active Controller - yii\rest\ActiveController ). in core code you can find find 4 actions for different headers GET,POST,PUT & DELETE .

'index' => ['GET', 'HEAD'],
'view' => ['GET', 'HEAD'],
'create' => ['POST'],
'update' => ['PUT', 'PATCH'],
'delete' => ['DELETE'],

基本上我们可以使用'HTTP Basic Authentication'进行身份验证

for authentication basically we can use 'HTTP Basic Authentication'