[英]Building a REST JSON API with Laravel
I need to build a mobile version of my application. 我需要构建应用程序的移动版本。 The mobile app is going to have the same functionality and for this I need to build an API for my web application that can be accessed from the mobile client.
移动应用程序将具有相同的功能,为此,我需要为Web应用程序构建一个可从移动客户端访问的API。
Let's have an example: I have a controller class called PostController
that is responsible for the posts in the application. 让我们举一个例子:我有一个名为
PostController
的控制器类,负责应用程序中的帖子。 This is a resource controller. 这是一个资源控制器。
Route::resource("users.posts", "PostController");
When the user access http://domain.com/users/{id}/posts/{id}
, he gets a rendered HTML response. 当用户访问
http://domain.com/users/{id}/posts/{id}
,他将获得呈现的HTML响应。 This is done in the PostController@show
method: 这是通过
PostController@show
方法完成的:
public function show($user_id, $post_id) {
$post = Post::findOrFail($post_id);
// other logic here
return view("post.show", ["post" => $post_id]);
}
But now the user launches his mobile application which queries http://api.domain.com/users/{id}/posts/{id}
. 但是,现在用户启动了查询
http://api.domain.com/users/{id}/posts/{id}
移动应用程序。 I know I could create a separate controller for the API, but this would result to code duplication. 我知道我可以为API创建一个单独的控制器,但这将导致代码重复。 Hard to maintain, not a clever idea.
难以维护,不是一个聪明的主意。
How do I make a JSON API that takes advantage of the existing controllers? 如何制作一个利用现有控制器的JSON API?
Maybe something like 也许像
public function show($user_id, $post_id) {
$post = Post::findOrFail($post_id);
// other logic here
if(is api.domain.com) {
return json
} else {
return view("post.show", ["post" => $post_id]);
}
}
I need to secure the API with OAuth and I have used the oauth2-server-laravel package. 我需要使用OAuth保护API,并且使用了oauth2-server-laravel软件包。
这主要是个人喜好,我会使用单独的控制器,因为我将api和网络应用视为单独的应用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.