当前位置:网站首页>Restful style
Restful style
2022-07-06 03:15:00 【Zyyyyu_】
RESTful style
What is? Api( Interface )
Api The full name is Application Programming Interface, That's the API , It encapsulates the functions we write into components , The purpose is to provide an application program interface for other program calls or other developers to access , And the calling developer does not need to access the source code and understand the internal logic and working principle , You can use this function directly .
Fore and aft end separation
In front and back separation mode , Front end developers need to call the interface provided by back-end developers , according to Api Document to call ,Api Documents can be accessed through Swagger Generate .
Front end separation is not just a development model , It is also a kind of Web Applied architectural patterns , Before development , The front and back-end personnel will first agree on the data interaction interface , Then develop in parallel , There will be no situation that one party needs to wait for the other party to complete the development before continuing the development .
There will be no page in the back-end project , Only responsible for providing interfaces to the front end , The front end only needs to concentrate on writing and rendering pages , Data call is provided by the backend REST Style interface is OK .
The front and rear separated cores : The front end is responsible for displaying , The back end is responsible for providing data , Mutual interference .
RESTful style
- Concept
RESTFUL It is a kind of design style and development method of network application program , be based on HTTP, have access to XML Format definition or JSON Format definition . The most common data format is JSON. because JSON Can be directly by JavaScript Read , therefore , Use JSON Format REST Style API Simple 、 Easy to read 、 Easy to use features .
REST It's not about technology , Represents a software architecture style ,REST yes Representational State Transfer For short , Chinese translation for “ Characterization state transfer ” or “ Represent layer state transformation ”. - resources
REST It's resource oriented , Each resource has a unique resource locator (URI). Every URI Represents a resource (resource), therefore URI There can be no verbs in , Only nouns , And the nouns used often correspond to the table name of the database . Generally speaking , The tables in the database are the same kind of records " aggregate "(collection), therefore URI The nouns in should also use the plural . - Request mode
Request mode | meaning |
---|---|
GET(SELECT) | Get resources from the server ( One or more ) |
POST(CREATE) | Create a new resource on the server |
PUT(UPDATE) | Update resources on the server ( Update full resources ) |
PATCH(UPDATE) | Update resources on the server , PATCH Update individual properties |
DELETE(DELETE) | Remove resources from server |
- And non REST Design comparison
Not Rest Design , We used to write like this :
http://localhost:8080/admin/getUser ( Query the user )
http://localhost:8080/admin/addUser ( New users )
http://localhost:8080/admin/updateUser ( Update user )
http://localhost:8080/admin/deleteUser ( Delete user )
summary : In different ways URL( It's mainly the use of verbs ) Do different things .Rest framework :
GET http://localhost:8080/admin/user ( Query the user )
POST http://localhost:8080/admin/user ( New users )
PUT http://localhost:8080/admin/user ( Update user )
DELETE http://localhost:8080/admin/user ( Delete user )
summary :URL Only specify resources , With HTTP Method verbs do different operations . use HTTP STATUS/CODE Define the operation result .
domain name
use api Keyword to identify the interface url
https://api.example.com
https://example.org/api/
notes : notice api The word , On behalf of the request url The link is to complete the data interaction between the front and back stationsedition
- Put the version information in URL in , Such as :
https://api.example.com/v1/
https://api.example.com/v2/
v1,v2 Represents the withdrawal of different data versions , The premise is that a data resource has multiple versions
- Put the version information in the request header .
- url route
- See everything on the Internet as a resource , All use nouns ( It's usually in the plural )
https://api.example.com/v1/zoos
https://api.example.com/v1/animals
https://api.example.com/v1/employees - stay url Do not appear verbs that operate resources in the link
Error model :https://api.baidu.com/delete-user - A special interface can have Verbs , Because these interfaces generally do not have a clear resource , Or the verb is the core meaning of the interface
https://api.baidu.com/place/search
https://api.baidu.com/login
method Request mode
GET : Get resources from the server ( One or more )
POST : Create a new resource on the server
PUT : Update resources on the server ( The client provides complete resources after the change )
PATCH : Update resources on the server ( Client provides changed properties )
DELETE : Remove resources from serverFilter
By means of url Pass search terms in the form of upload parameters
https://api.example.com/v1/zoos?limit=10: Specify the number of returned records
https://api.example.com/v1/zoos?offset=10: Specify where to start the return record
https://api.example.com/v1/zoos?page=2&per_page=100: Specify page , And the number of records per page
https://api.example.com/v1/zoos?sortby=name&order=asc: Specifies which attribute to sort the returned results by , And sort order
https://api.example.com/v1/zoos?animal_type_id=1: Specify filter criteriaStatus code
200 OK - [GET]: The server successfully returned the data requested by the user , The operation is idempotent (Idempotent).
201 CREATED - [POST/PUT/PATCH]: User created or modified data successfully .
202 Accepted - [*]: Indicates that a request has entered the background queue ( Asynchronous task )
204 NO CONTENT - [DELETE]: User successfully deleted data .
301: Permanent redirection
302: Redirect temporarily
400 INVALID REQUEST - [POST/PUT/PATCH]: There is an error in the user's request , The server does not create or modify data , The operation is idempotent .
401 Unauthorized - [*]: Indicates that the user does not have permission ( token 、 user name 、 Wrong password ).
403 Forbidden - [*] Indicates that the user is authorized ( And 401 Error relative ), But access is forbidden .
404 NOT FOUND - [*]: The user's request is for a record that doesn't exist , The server is not operating , The operation is idempotent .
406 Not Acceptable - [GET]: Format requested by user is not available ( Such as user request JSON Format , But only XML Format ).
410 Gone -[GET]: User requested resource is permanently deleted , And it won't come back .
422 Unprocesable entity - [POST/PUT/PATCH] When creating an object , A validation error occurred .
500 INTERNAL SERVER ERROR - [*]: Server error , The user will not be able to determine whether the request was successful .
RESTful Interface code example
package com.zy.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.zy.demo.entity.OrderEntity;
import com.zy.demo.demo.service.OrderService;
@RequestMapping("restful/order")
@RestController
public class OrderController {
@Autowired
private OrderService orderService;
@GetMapping(value = "{id}")
//@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<OrderEntity> queryOrderById(@PathVariable("id") Long id) {
try {
OrderEntity entity = orderService.queryOrderById(id);
if (null == entity) {
// Resource does not exist , Respond to 404
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
// 200
// return ResponseEntity.status(HttpStatus.OK).body(entity);
return ResponseEntity.ok(entity);
} catch (Exception e) {
e.printStackTrace();
}
// 500
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
@PostMapping
//@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Void> saveOrder(OrderEntity entity) {
try {
orderService.saveOrder(entity);
return ResponseEntity.status(HttpStatus.CREATED).build();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 500
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
@PutMapping
//@RequestMapping(method = RequestMethod.PUT)
public ResponseEntity<Void> updateOrder(OrderEntity entity) {
try {
orderService.updateOrder(entity);
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
} catch (Exception e) {
e.printStackTrace();
}
// 500
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
@DeleteMapping
//@RequestMapping(method = RequestMethod.DELETE)
public ResponseEntity<Void> deleteOrder(@RequestParam(value = "id") Long id) {
try {
OrderEntity entity = orderService.queryOrderById(id);
if (null == entity) {
// There is no return 404
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
orderService.deleteOrderById(id);
// 204
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
} catch (Exception e) {
e.printStackTrace();
}
// 500
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
summary
RESTful It's just a style of software architecture 、 Design style , Not the standard , It just provides a set of design principles and constraints , It is mainly used for client and server interaction software . The software designed based on this style can be more brief , More layers , It is easier to implement caching and other mechanisms .
Use RESful The advantage of style development is
- Make the request path simpler
- Pass on 、 It is more convenient to obtain parameter values , The framework automatically casts types
- Through path variables @PathVariable The type of , Access parameters can be constrained .
- If the parameter value does not match the definition type , The corresponding method cannot be accessed , Report errors 400 Wrong request .
- Security , Pass parameter values directly in the request path , With slash / Separate , The parameter variable names passed to the method are not exposed .
- Efficient , Easier implementation of caching , Make response more efficient .
RESTful Simple style , Efficient , Security , Become web service Standard configuration for development .
边栏推荐
- 1. Dynamic parameters of function: *args, **kwargs
- . Net 6 and Net core learning notes: Important issues of net core
- 【概念】Web 基础概念认知
- SD card reports an error "error -110 whilst initializing SD card
- I sorted out a classic interview question for my job hopping friends
- Custom attribute access__ getattribute__/ Settings__ setattr__/ Delete__ delattr__ method
- jsscript
- [concept] Web basic concept cognition
- canvas切积木小游戏代码
- Research on cooperative control of industrial robots
猜你喜欢
canvas切积木小游戏代码
适合程序员学习的国外网站推荐
指针笔试题~走近大厂
Jenkins basic knowledge ----- detailed explanation of 03pipeline code
IPv6 comprehensive experiment
【Kubernetes 系列】一文學會Kubernetes Service安全的暴露應用
Linear programming matlab
Fault analysis | analysis of an example of MySQL running out of host memory
Getting started with applet cloud development - getting user search content
[network security interview question] - how to penetrate the test file directory through
随机推荐
深度解析指针与数组笔试题
js凡客banner轮播图js特效
Handwriting database client
BUUCTF刷题笔记——[极客大挑战 2019]EasySQL 1
2022工作中遇到的问题四
深入刨析的指针(题解)
适合程序员学习的国外网站推荐
[padding] an error is reported in the prediction after loading the model weight attributeerror: 'model' object has no attribute '_ place‘
An article about liquid template engine
Audio audiorecord binder communication mechanism
深入探究指针及指针类型
How to write compile scripts compatible with arm and x86 (Makefile, cmakelists.txt, shell script)
Era5 reanalysis data download strategy
建模规范:命名规范
SD卡報錯“error -110 whilst initialising SD card
Codeworks 5 questions per day (1700 average) - day 6
银行核心业务系统性能测试方法
Microservice registration and discovery
JS音乐在线播放插件vsPlayAudio.js
Fault analysis | analysis of an example of MySQL running out of host memory