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.

  1. Best Practice # 1: Use HTTP VERBS to determine action to be taken
  2. Best Practice # 2: API Versioning
  3. Best Practice # 3: Use plurals to describe resources
  4. Best Practice # 4: Use query strings to build relations
  5. Best Practice # 5: Partial responses
  6. Best Practice # 6: Response Codes and Error Handling
  7. Best Practice # 7: Limit the number of request in a given time period from the same IP Address
  8. Best Practice # 8: Use OAuth latest version for authentication
  9. Best Practice # 9: use JSON as the default
  10. 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

  1. Open /app/Http/routes.php
  2. 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的更多相关文章

  1. 拿nodejs快速搭建简单Oauth认证和restful API server攻略

    拿nodejs快速搭建简单Oauth认证和restful API server攻略:http://blog.csdn.net/zhaoweitco/article/details/21708955 最 ...

  2. 【3】创建一个简单的Laravel例子

    现在我们来创建一个Laravel的例子来帮助理解 1.首先打开app/Http/routes.php文件,在里边写上一条路由: 2.创建一个控制器,有两种方法 ①在app/Http/Controlle ...

  3. 实现一个简单的Laravel的dd库

    前几天写了一个简单的Laravel的dd库. 为什么自己要写一个这样的库? Laravel本身已经实现了自己的输出dd函数,但是我之所以要写这样一个库,一来是因为Laravel本身对这个库的封装没办法 ...

  4. [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 ...

  5. Gin实战:Gin+Mysql简单的Restful风格的API(二)

    上一篇介绍了Gin+Mysql简单的Restful风格的API,但代码放在一个文件中,还不属于restful风格,接下来将进行进一步的封装. 目录结构 ☁ gin_restful2 tree . ├─ ...

  6. Laravel POST请求API接口 使用validate表单验证返回欢迎页

    突然遇到的问题  就是使用Laravel进行开发API接口的时候  发现在表单验证不通过的时候返回了登录页 猜测问题应该是因为表单验证失败后进行了重定向导致的 因为返回状态码200 网上找了好久没找到 ...

  7. 简单快捷地测试 JPush API

    随着 JPush API v3版本的推出,加上之前开放的 Report API,JPush API 逐渐切换为比较好的符合 REST API 的规范,从而也很容易地使用一般的 HTTP/REST 工具 ...

  8. 利用Laravel 搭建oauth2 API接口 附 Unauthenticated 解决办法

    利用Laravel 搭建oauth2 API接口 要求 laravel 5.4以上 安装 $ composer require laravel/passport 在配置文件 config/app.ph ...

  9. laravel jwt 做API 退出登录(注销) 该怎么弄? 如何让token失效

    laravel jwt 做API 退出登录(注销) 该怎么弄? 如何让token失效 php框架 laravel 2.1k 次浏览 问题对人有帮助,内容完整,我也想知道答案0问题没有实际价值,缺少关键 ...

随机推荐

  1. NHibernate初探(1)

    1 NHibernate是ORM的一种. 是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术.ORM是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系数据库中.本质上 ...

  2. LightOJ 1079 Just another Robbery 概率背包

    Description As Harry Potter series is over, Harry has no job. Since he wants to make quick money, (h ...

  3. 如何用Linux的命令正确识别cpu的个数和核数【转】

    判断依据: 1.具有相同core id的cpu是同一个core的超线程. 2.具有相同physical id的cpu是同一颗cpu封装的线程或者cores. 英文版: 1.Physical id an ...

  4. 解决Fiddler无法抓到手机的会话包

    解决Fiddler无法抓到手机的会话包   使用Fiddler抓手机的会话包涉及多个方面,所以容易出现无法抓取包的情况.遇到这类问题,需要按照以下顺序进行检查和排除.   (1)在Fiddler中设置 ...

  5. C Golden gun的巧克力

    Time Limit:1000MS  Memory Limit:65535K 题型: 编程题   语言: 无限制 描述 众所周知,13级有尊大神Golden gun,人称根叔,简称金枪!众立志进校队的 ...

  6. 基于Extjs的web表单设计器 第六节——界面框架设计

    基于Extjs的web表单设计器 基于Extjs的web表单设计器 第一节 基于Extjs的web表单设计器 第二节——表单控件设计 基于Extjs的web表单设计器 第三节——控件拖放 基于Extj ...

  7. Sql不区分大小写查询

    select a.* from Pair_User  a where 1=1   and   UPPER(a.UserID) like 'EMH1001%' collate Chinese_PRC_C ...

  8. ural 1221. Malevich Strikes Back!

    1221. Malevich Strikes Back! Time limit: 1.0 secondMemory limit: 64 MB After the greatest success of ...

  9. BZOJ1767 : [Ceoi2009]harbingers

    设d[i]表示i到1的距离 f[i]=w[i]+min(f[j]+(d[i]-d[j])*v[i])=w[i]+d[i]*v[i]+min(-d[j]*v[i]+f[j]) 对这棵树进行点分治,每次递 ...

  10. kvm快照

    Kvm快照: 1.基于lvm的快照 2.kvm自带的快照功能(需要qcow2 磁盘文件才支持快照) 关闭kvm虚拟机: 查看磁盘文件信息: [root@super67 ~]# qemu-img inf ...