我已经开始创建RESTful API(我已经尽力了,我正在尝试遵循这些模式),但是我偶然发现了一个我不确定如何处理的场景。我将解释当前的结构:
我的应用程序有4个控制器:
以“客户”控制器为例,我定义了以下操作:
这是客户控制器的完整代码:
namespace App\Http\Controllers;
use App\Customer;
use Illuminate\Http\Request;
class CustomerController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return Customer::all();
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$customer = Customer::create($request->all());
return response()->json($customer, 201);
}
/**
* Display the specified resource.
*
* @param \App\Customer $customer
* @return \Illuminate\Http\Response
*/
public function show(Customer $customer)
{
return $customer;
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Customer $customer
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Customer $customer)
{
$customer->update($request->all());
return response()->json($customer, 200);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Customer $customer
* @return \Illuminate\Http\Response
*/
public function destroy(Customer $customer)
{
$customer->delete();
return response()->json(null, 204);
}
}
该代码在其他控制器中非常相似。同样重要的是要注意:
问题从这里开始
我需要在前端显示一个摘要页面,其中包含所有客户数据(姓名,电子邮件,注册日期等),一个框显示付款金额,另一个框显示日志中的条目数。
我需要提出3个请求吗? (一个是/ customers / id,另一个是客户/ id /付款,另一个是客户/ id /日志)
如果我在customer / id调用中返回了所有与客户有关的数据,是否违反了RESTful约定?
答案 0 :(得分:1)
我正在使用通用性,但我的答案仍然与您的问题有关。根据REST术语(可以在https://apigility.org/documentation/intro/first-rest-service#terminology中找到),您所谈论的是实体和集合。
/customers/id - entity,
/customers/id/payments - collection,
/customers/id/logs - collection.
这些是3个不同的请求。因此,是的,您需要提出3个不同的请求。
但是,说实话,如果您不需要在payments
和logs
上进行分页,则只能对/ customers / id发出一个请求,并且在响应中可以包含带有数组的字段>
{
"_links": {
"self": {
"href": "http://localhost:8080/status/3c10c391-f56c-4d04-a889-bd1bd8f746f0"
}
},
"id": "3c10c391-f56c-4d04-a889-bd1bd8f746f0",
...
_payments: [
...
],
_logs: [
...
],
}
已更新(与评论重复,供将来的访问者使用)。
此外,您还应注意DTO。我想这个链接会很有趣https://stackoverflow.com/a/36175349/1581741。
Upd2 。
目前,我将这样处理您的收藏集/customers/id/payments
:
/payments?user_id=123
其中user_id
是payments
表上的过滤字段。
答案 1 :(得分:0)
我认为您的问题是将REST API与数据库混淆。他们不必遵循相同的结构。如果您需要REST API,可以轻松返回GET /customers/{id}
的整个嵌套JSON。