[英]RESTful API: Data from multiple endpoints in one single view
我已经开始创建一个 RESTful API(好吧,我已经尽力了,我正在尝试遵循这些模式)并且我偶然发现了一个我不确定如何处理的场景。 我将解释当前的结构:
我的应用程序有 4 个控制器:
以客户控制器为例,我定义了以下操作:
这是 Customer 控制器的完整代码:
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,另一个到customers/id/payments,另一个到customers/id/logs)
如果我在 customer/id 调用中返回所有与客户相关的数据,我是否违反了 RESTful 约定?
我正在使用apigility,但我的回答仍然与您的问题有关。 根据 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 。
更新2 。
目前,我对待您的收款/customers/id/payments
是这样的:
/payments?user_id=123
其中user_id
是payments
表上的过滤字段。
我认为您将 REST API 与数据库混淆的问题。 它们不必遵循相同的结构。 如果您需要 REST API,您可以轻松地为GET /customers/{id}
返回整个嵌套的 JSON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.