【转】简单的 Laravel 5 REST API
Introduction
Almost all successful internet based companies have APIs. API is an acronym for Application Programming Interface. APIs allows different systems to communicate with one another. Let’s say you have developed an android application for our online store. The API can be used to retrieve data from the online store and display it in the mobile application. The API can also be used to process orders from remote clients such as mobile applications, other websites etc.
Topics to be covered
We will cover the following topics
- What is a RESTful API?
- REST API Best Practices
- Larashop API
What is a RESTful API?
REST is the acronym for Representational State Transition. It is a software architectural design for building scalable web services. REST APIs allow systems to communicate over HTTP using HTTP verbs. HTTP GET is used to get resources, POST used to create new resources, PUT to update existing ones and DELETE to delete existing resources.
REST API Best Practices
This is a summary from the blog post we posted on Kode Blog 10 REST API Design Best Practices That Will Make Developers Love Your API. Read the article for detailed explanations of this summary.
- Best Practice # 1: Use HTTP VERBS to determine action to be taken
- Best Practice # 2: API Versioning
- Best Practice # 3: Use plurals to describe resources
- Best Practice # 4: Use query strings to build relations
- Best Practice # 5: Partial responses
- Best Practice # 6: Response Codes and Error Handling
- Best Practice # 7: Limit the number of request in a given time period from the same IP Address
- Best Practice # 8: Use OAuth latest version for authentication
- Best Practice # 9: use JSON as the default
- Best Practice # 10: Cache GET results for less frequently changing data
Larashop API
For now, we will only display the products and categories. Our API will implement basic authentication only. Future tutorial updates will include more functionality.
Our API will have the following URLs. All the URLs will use the HTTP verb GET
S/N | Resource | URL | Description | Status Code |
---|---|---|---|---|
1 | Product | /api/v1/products | List products | 200 |
2 | Product | /api/v1/products/1 | List product with id 1 | 200 |
3 | Category | /api/v1/categories | List categories | 200 |
4 | Category | /api/v1/categories/1 | List category with id 1 | 200 |
Let’s now create the routes that will give us
- Open
/app/Http/routes.php
- Add the following routes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// API routes...
Route::get('/api/v1/products/{id?}', ['middleware' => 'auth.basic', function($id = null) {
if ($id == null) {
$products = App\Product::all(array('id', 'name', 'price'));
} else {
$products = App\Product::find($id, array('id', 'name', 'price'));
}
return Response::json(array(
'error' => false,
'products' => $products,
'status_code' => 200
));
}]); Route::get('/api/v1/categories/{id?}', ['middleware' => 'auth.basic', function($id = null) {
if ($id == null) {
$categories = App\Category::all(array('id', 'name'));
} else {
$categories = App\Category::find($id, array('id', 'name'));
}
return Response::json(array(
'error' => false,
'user' => $categories,
'status_code' => 200
));
}]);
HERE,
Route::get('/api/v1/products/{id?}', ['middleware' => 'auth.basic', function($id = null)
defines a RESTful URL for version 1 of the API. The requested resource is Products. {id?} specifies an optional parameter. The id is used to retrieve a single product. The API uses basic authentication- The routes are calling the respective models to retrieve the data from the database.
return Response::json(…)
returns the results in JSON format.
Load the following URL in your web browser
1
http://localhost/larashop/public/api/v1/products
You will get the following basic Authentication login window
User a registered email address and password from the previous tutorial on Authetication You will get the following results
Summary
Building a basic REST API in Laravel is no more than retrieving data using models and formatting the response to JSON. The future tutorial updates will build a fairly complex API that will do more.
Tutorial History
Tutorial version 1: Date Published 2015-08-31
【转】简单的 Laravel 5 REST API的更多相关文章
- 拿nodejs快速搭建简单Oauth认证和restful API server攻略
拿nodejs快速搭建简单Oauth认证和restful API server攻略:http://blog.csdn.net/zhaoweitco/article/details/21708955 最 ...
- 【3】创建一个简单的Laravel例子
现在我们来创建一个Laravel的例子来帮助理解 1.首先打开app/Http/routes.php文件,在里边写上一条路由: 2.创建一个控制器,有两种方法 ①在app/Http/Controlle ...
- 实现一个简单的Laravel的dd库
前几天写了一个简单的Laravel的dd库. 为什么自己要写一个这样的库? Laravel本身已经实现了自己的输出dd函数,但是我之所以要写这样一个库,一来是因为Laravel本身对这个库的封装没办法 ...
- [Laravel] 14 - REST API: Laravel from scratch
前言 一.基础 Ref: Build a REST API with Laravel API resources Goto: [Node.js] 08 - Web Server and REST AP ...
- Gin实战:Gin+Mysql简单的Restful风格的API(二)
上一篇介绍了Gin+Mysql简单的Restful风格的API,但代码放在一个文件中,还不属于restful风格,接下来将进行进一步的封装. 目录结构 ☁ gin_restful2 tree . ├─ ...
- Laravel POST请求API接口 使用validate表单验证返回欢迎页
突然遇到的问题 就是使用Laravel进行开发API接口的时候 发现在表单验证不通过的时候返回了登录页 猜测问题应该是因为表单验证失败后进行了重定向导致的 因为返回状态码200 网上找了好久没找到 ...
- 简单快捷地测试 JPush API
随着 JPush API v3版本的推出,加上之前开放的 Report API,JPush API 逐渐切换为比较好的符合 REST API 的规范,从而也很容易地使用一般的 HTTP/REST 工具 ...
- 利用Laravel 搭建oauth2 API接口 附 Unauthenticated 解决办法
利用Laravel 搭建oauth2 API接口 要求 laravel 5.4以上 安装 $ composer require laravel/passport 在配置文件 config/app.ph ...
- laravel jwt 做API 退出登录(注销) 该怎么弄? 如何让token失效
laravel jwt 做API 退出登录(注销) 该怎么弄? 如何让token失效 php框架 laravel 2.1k 次浏览 问题对人有帮助,内容完整,我也想知道答案0问题没有实际价值,缺少关键 ...
随机推荐
- Android JNI(转)
JNI,全称Java Native Interface,是用于让运行在JVM中的Java代码和运行在JVM外的Native代码(主要是C或者C++)沟通的桥梁.代码编写者即可以使用JNI从Java的程 ...
- LightOJ 1248 Dice (III) 概率
Description Given a dice with n sides, you have to find the expected number of times you have to thr ...
- loj 1308(点双连通分量应用)
题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=27016 题意:求一个连通图去掉任意一个点以及与它相连的边,图中的所 ...
- linux下用top命令查看cpu利用率超过100%
今天跑了一个非常耗时的批量插入操作..通过top命令查看cpu以及内存的使用的时候,cpu的时候查过了120%..以前没注意..通过在top的情况下按大键盘的1,查看的cpu的核数为4核. 通过网上查 ...
- ajax请求node.js接口时出现 No 'Access-Control-Allow-Origin' header is present on the requested resource错误
ajax请求node.js接口出现了如下的错误: XMLHttpRequest cannot load http://xxx.xxx.xx.xx:8888/getTem?cityId=110105&a ...
- nodeAPI--TCP
Node HTTP服务器是构建与Node TCP服务器之上的,即http.Server继承自net.Server; TCP特性: 面向连接的通信和保证顺序的传递: IP的协议是面向无连接,且数据包送达 ...
- UIBarButtonItem不能获取frame
在使用KxMenu这个厉害的控件做竖直列表的时候,发现UIBarButtonItem不能获取到frame,UIBarButtonItem是NSObject的子类,他不是一个uiresponed或者ui ...
- 密码等级:至少包含字母、大小写数字、字符中的两种 JS实现方案
前言 密码,如果设置的太简单,很容易就被攻破,所以很多网站将密码设置的要求设置的挺严格,一般是字母.数字.字符3选2,区分大小写.对于设置得太简单的密码,予以错误提示.或者予以密码等级(低中高)显示, ...
- Remove Duplicates from Sorted List II leetcode java
题目: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct ...
- kail-linux 下载地址
http://archive-6.kali.org/kali-images/kali-2016.1/kali-linux-2016.1-i386.iso 选择debian 32/64bit安装 开始启 ...