1. Rest and RestFul
REST (English: Representational State Transfer, referred to as REST), Representational State Transfer, refers to a set of architectural principles.
Restful: a web service or web application that complies with the rest principle.
2. Six elements of API design
Resource path (URI), HTTP verb (Method), query string, status code, error, result
1) Resource path URI
Resources: all data saved in the server (such as music / video / articles / personal information...) are server-side resources (resources in the project usually refer to a piece of data in the data table)
URI (Uniform Resource Identifier): uniform resource identifier, including URL and URN.
URL (uniform resource locator): Uniform Resource Locator
URN (Uniform Resource Name): Uniform Resource Name
In HTTP protocol, URI is composed as follows
Schema://host[:port]/path[?query-string]
Schema: the protocol type used, such as http/https/ftp
Host: host domain name or IP
Port: port number (optional)
path: path
Query string: query parameters (optional)
example:
http://www.tpshop.com/users
https://www.tpshop.com:8080/users?id=100
2) HTTP verb (request mode)
For resources, there are generally four operations, curd (add / delete / modify / query)
GET: GET the resource (one or more) from the server
POST: create a new resource on the server
PUT: when the server updates the resource, the server returns the complete attribute
DELETE: DELETE resource from server
3) Filter information
It is also commonly referred to as a request parameter or query string.
4) Response status code
The information returned by the server is used to tell the client the operation result.
Common status codes:
Status code | meaning | explain |
---|---|---|
200 | OK | The operation is successful and the data is returned |
201 | CREATED | New successfully |
204 | NO CONTENT | Delete succeeded |
400 | BAD REQUEST | Request syntax error |
403 | Forbidden | Request resources without permission |
404 | NOT FOUND | The requested resource was not found |
GET
200(OK) - Indicates that it has been issued in the response 204((no content) - Resource empty representation 301(Moved Permanently) - Resource URI Updated 303(See Other) - Others (e.g., load balancing) 304(not modified)- Resource not changed (CACHE) 400 (bad request)- Refers to a bad request (e.g., parameter error) 404 (not found)- Resource does not exist 406 (not acceptable)- The server does not support the required representation 500 (internal server error)- General error response 503 (Service Unavailable)- The server is currently unable to process the request
POST
200(OK)- If an existing resource has been changed 201(created)- If a new resource is created 202(accepted)- Processing request accepted but not completed (asynchronous processing) 301(Moved Permanently)- Resource URI Updated 303(See Other)- Others (e.g., load balancing) 400(bad request)- Bad request 404 (not found)- Resource does not exist 406 (not acceptable)- The server does not support the required representation 409 (conflict)- Generic conflict 412 (Precondition Failed)- Precondition failure (such as conflict when performing condition update) 415 (unsupported media type)- The received representation is not supported 500 (internal server error)- General error response 503 (Service Unavailable)- The service is currently unable to process the request
PUT
200 (OK)- If the resource already exists, it will be changed 201 (created)- If a new resource is created 301(Moved Permanently)- Resource URI Changed 303 (See Other)- Others (e.g., load balancing) 400 (bad request)- Bad request 404 (not found)- Resource does not exist 406 (not acceptable)- The server does not support the required representation 409 (conflict)- Generic conflict 412 (Precondition Failed)- Precondition failure (such as conflict when performing condition update) 415 (unsupported media type)- The received representation is not supported 500 (internal server error)- General error response 503 (Service Unavailable)- The service is currently unable to process the request
DELETE
200 (OK)- The resource has been deleted 301 (Moved Permanently)- Resource URI Changed 303 (See Other)- Others, such as load balancing 400 (bad request)- Bad request 404 (not found)- Resource does not exist 409 (conflict)- Generic conflict 500 (internal server error)- General error response 503 (Service Unavailable)- The server is currently unable to process the request
5) Error message
If the status code is 4xx or 5xx, you need to tell the client the corresponding error message Usually returned in Json format:
{ "error": ""Error message", }
6) Return results
For different operations, the results returned by the service should meet such specifications
GET /collections - returns a list of resources (array)
GET /collections/:id - returns a single resource eg. /collections/1
POST /collections - returns the newly generated resource
PUT /collections/:id - returns the complete attribute of the resource
DELETE /collections/:id - return 204 status code + empty document
In actual development, the status code, error information and return data are usually put into the return result.
such as
{"code":200, 'msg':'success', "data":{"id":1,"goods_name":"tp"}}
3. RestFul interface design style
Resource routing in TP framework
Manual - Routing - resource routing, manual - controller - resource controller
① Create api module
php think build --module api
② Create news controller
php think make:controller api/News
③ Set route (application/route.php)
\think\Route::resource('news','api/news');
It is equivalent to setting the following routes respectively:
\think\Route::get('news','api/news/index'); \think\Route::get('news/create','api/news/create'); \think\Route::post('news','api/news/save'); \think\Route::get('news/:id','api/news/read'); \think\Route::get('news/:id/edit','api/news/edit'); \think\Route::put('news/:id','api/news/update'); \think\Route::delete('news/:id','api/news/delete');
After setting, 7 routing rules will be registered automatically, as follows:
identification | Request type | Generate routing rules | Corresponding operation method (default) |
---|---|---|---|
index | GET | news | index |
create | GET | news/create | create |
save | POST | news | save |
read | GET | news/:id | read |
edit | GET | news/:id/edit | edit |
update | PUT | news/:id | update |
delete | DELETE | news/:id | delete |
④ Modify the News controller to return json format data
<?php namespace app\api\controller; use think\Controller; use think\Request; class News extends Controller { /** * Show resource list * * @return \think\Response */ public function index() { return json(['code' => 200, 'msg' => 'success', 'data'=>'index']); } /** * The create resource form page is displayed * * @return \think\Response */ public function create() { return json(['code' => 200, 'msg' => 'success', 'data'=>'create']); } /** * Save the new resource * * @param \think\Request $request * @return \think\Response */ public function save(Request $request) { return json(['code' => 200, 'msg' => 'success', 'data'=>'save']); } /** * Displays the specified resource * * @param int $id * @return \think\Response */ public function read($id) { return json(['code' => 200, 'msg' => 'success', 'data'=>'read']); } /** * The edit resource form page is displayed * * @param int $id * @return \think\Response */ public function edit($id) { return json(['code' => 200, 'msg' => 'success', 'data'=>'edit']); } /** * Save updated resources * * @param \think\Request $request * @param int $id * @return \think\Response */ public function update(Request $request, $id) { return json(['code' => 200, 'msg' => 'success', 'data'=>'update']); } /** * Delete the specified resource * * @param int $id * @return \think\Response */ public function delete($id) { return json(['code' => 200, 'msg' => 'success', 'data'=>'delete']); } }
Access the following seven addresses through postman:
Request mode Request address get http://www.tpshop.com/news get http://www.tpshop.com/news/create post http://www.tpshop.com/news get http://www.tpshop.com/news/33 get http://www.tpshop.com/news/33/edit put http://www.tpshop.com/news/33 delete http://www.tpshop.com/news/33
4. ajax request restful interface
In the public directory, create the test file API html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajax request restful Interface</title> <script src="/static/admin/js/jquery-1.8.1.min.js"></script> </head> <body> <input type="button" id="index" value="index"> <input type="button" id="create" value="create"> <input type="button" id="save" value="save"> <input type="button" id="read" value="read"> <input type="button" id="edit" value="edit"> <input type="button" id="update" value="update"> <input type="button" id="delete" value="delete"> <script> $(function(){ $('#index').click(function(){ $.ajax({ "url":"/news", "type":"get", "data":"", "dataType":"json", "success":function(res){ console.log(res); } }); }); $('#create').click(function(){ $.ajax({ "url":"/news/create", "type":"get", "data":"", "dataType":"json", "success":function(res){ console.log(res); } }); }); $('#save').click(function(){ $.ajax({ "url":"/news", "type":"post", "data":"", "dataType":"json", "success":function(res){ console.log(res); } }); }); $('#read').click(function(){ $.ajax({ "url":"/news/33", "type":"get", "data":"", "dataType":"json", "success":function(res){ console.log(res); } }); }); $('#edit').click(function(){ $.ajax({ "url":"/news/33/edit", "type":"get", "data":"", "dataType":"json", "success":function(res){ console.log(res); } }); }); $('#update').click(function(){ $.ajax({ "url":"/news/33", "type":"put", "data":"", "dataType":"json", "success":function(res){ console.log(res); } }); }); $('#delete').click(function(){ $.ajax({ "url":"/news/33", "type":"delete", "data":"", "dataType":"json", "success":function(res){ console.log(res); } }); }); }); </script> </body> </html>