Why create a separate application for RESTful API?

2019-03-20 03:52发布

问题:

In the guide for Yii 2 it is said:

While not required, it is recommended that you develop your RESTful APIs as a separate application, different from your Web front end and back end for easier maintenance.

Source: RESTful Web Services - Quick Start

What does this mean? Would this be a completely different application or can it be in the same folder as the 'normal' web application? I've just started with my application so I can change things easily, more or less. But I'm wondering: if I would create another application than my business logic would not be accessible.

Why and how I should create another application? And when it's not required?

回答1:

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

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

Here is good example for RESTful API with advance template

Setup RESTful API in Yii2(budiirawan)

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'],

for authentication basically we can use 'HTTP Basic Authentication'



回答2:

This article explain the idea and the why , also it provide you a starter project called "yii2-advanced-api": http://budiirawan.com/setup-restful-api-yii2/



回答3:

IMHO if you need REST API for Angular.js or Knockout.js AJAX calls on your website it's an overhead to do it as a separate application. Because you will have issues with cross-domain AJAX calls (especially for POST requests).

I think it's enough to make a module (API) in the frontend for REST API



标签: api rest yii2