Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the RESTful specifications of java

2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article focuses on "what are the RESTful specifications of java". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "what are the RESTful specifications of java?"

What is RESTful?

A software architecture style, design style, rather than a standard, only provides a set of design principles and constraints. It is mainly used for client and server interaction class software. Software designed based on this style can be more concise, more hierarchical, and easier to implement caching and other mechanisms.

I. URI specification

1. No uppercase.

two。 Use the middle bar-no lower bar _

3. Parameter list is encode.

Nouns in 4.URI denote a collection of resources in the plural.

5. In RESTful architecture, each URL represents a resource, so there can be no verbs in the URL, only nouns (verbs can be used in special cases), and the nouns often correspond to the table names of the database.

Resource collection vs single resource

URI represents resources in two ways: a collection of resources and a single resource.

Resource collection:

/ zoos / / all zoos

/ zoos/1/animals / / all animals in a zoo with an id of 1

Single resource:

Zoo with a zoos/1//id of 1

/ zoos/1;2;3//id is the zoo of 1, 2, 2, 3

Avoid overly hierarchical URI

Express the hierarchy in url, which is used to navigate objects by entity association, usually according to id.

Too deep navigation can easily lead to url expansion and difficult maintenance, such as GET/ zoos/1/areas/3/animals/4. Try to use query parameters instead of entity navigation in the path, such as GET/animals?zoo=1&area=3.

II. Version

The version number of API should be put into URI

Https://api.example.com/v1/zoos

3. RequestHTTP method

Using the standard HTTP method to CRUD the resource:

GET: query (fetching one or more resources from the server)

GET / zoos

GET / zoos/1

GET/zoos/1/employees

POST: create a single new resource. POST is generally initiated to the "resource collection" type uri

POST/animals / / New Animals

POST/zoos/1/employees / / hires staff for zoos with id 1

PUT: update a single resource (full), and the client provides a complete updated resource. In contrast, PATCH,PATCH is responsible for partial updates, and the client provides those fields to update. PUT/PATCH generally initiates to "single resource" uri.

PUT/animals/1

PUT / zoos/1

DELETE: deletin

DELETE/zoos/1/employees/2

DELETE/zoos/1/employees/2;4;5

DELETE/zoos/1/animals / / Delete all animals in zoos with id 1

HEAD / OPTION/ PATCH doesn't use much, so it doesn't explain much.

HEAD: get the metadata of a resource

OPTIONS: get information about which properties of the resource can be changed by the client

PATCH: update resources on the server (client provides changed properties)

Security and idempotency

1. Security: does not change the state of resources and can be understood as read-only

two。 Idempotency: once executed and N times executed, the effect on resource state change is equivalent.

.

Security.

Idempotency

GET

POST

×

×

PUT

×

DELETE

×

Security and idempotency do not guarantee that repeated requests will get the same response. Take DELETE as an example, the first time DELETE returns 200 indicates that the deletion is successful, and the second time 404 indicates that the resource does not exist, which is allowed.

Complex query

The query can piggyback the following parameters:

.

Example

Remarks

Filter condition

? type=1&age=16

Allow certain uri redundancy, such as / zoos/1 and / zoos?id=1

Sort

? sort=age&order=asc

Specify which attribute the returned results are sorted by, and the sort order

Projection

? whitelist=id,name,email

Pagination

? Page=2&per_page=100

Specify which page and the number of records per page

Bookmarker

Frequently used, complex query tagging to reduce maintenance costs.

Such as: GET / trades?status=closed&sort=created,desc

Shortcut: GET / trades#recently-closed or GET / trades/recently-closed

Status code

Some of the status codes and prompts returned by the server to the user are as follows (square brackets are the HTTP verbs corresponding to the status code).

§200 OK-[GET]: the server successfully returns the data requested by the user, which is idempotent (Idempotent).

§201 CREATED-[POST/PUT/PATCH]: the user created or modified the data successfully.

§202 Accepted-[*]: indicates that a request has entered the background queue (asynchronous task)

§204 NO CONTENT-[DELETE]: user deleted data successfully.

§400 INVALID REQUEST-[POST/PUT/PATCH]: there is an error in the request made by the user, and the server does not create or modify data, which is idempotent.

§401 Unauthorized-[*]: indicates that the user does not have permissions (token, user name, password error).

§403 Forbidden-[*] indicates that the user is authorized (as opposed to the 401 error), but access is prohibited.

§404 NOT FOUND-[*]: the request made by the user is for a record that does not exist, and the server does not operate, which is idempotent.

§406 Not Acceptable-[GET]: the format of the user request is not available (for example, the user requests the JSON format, but only the XML format).

§410 Gone-[GET]: the resource requested by the user is permanently deleted and will not be obtained again.

§422 Unprocesable entity-[POST/PUT/PATCH] A validation error occurred while creating an object.

§500 INTERNAL SERVER ERROR-[*]: an error occurred on the server and the user will not be able to judge whether the request was successful or not.

For a complete list of status codes, see here

URI failure

With the development of the system, there will always be some API failures or migrations. For the failed API, 404 not found or 410 gone; pairs of migrated API will be returned, and 301 redirection will be returned.

4. Response1. Do not pack:

The body of response is data directly, so don't do redundant packaging. Example of error:

{

"success": true

"data": {"id": 1, "name": "xiaotuan"}

}

two。 The data format after successful processing of each HTTP method:

Response format

GET

Single object, collection

POST

New successful objects

PUT/PATCH

Objects that were updated successfully

DELETE

Vbl.

5. Error handling

1. Do not have an error but give a 2xx response, and the client may cache a successful http request

two。 Set the http status code correctly and do not customize it

3. Provided by Response body

That is, error is used as the key name and error message as the key value in the returned information.

1) incorrect code (log / problem tracing)

2) error description text (shown to the user).

Say a little more about the implementation of the third point:

The Java server usually uses exceptions to denote RESTful API errors. API may throw two types of exceptions: business exceptions and non-business exceptions. A business exception is thrown by its own business code, indicating that the preconditions of a use case are not met, business rules conflict, and so on, such as parameter verification failure, permission verification failure. Non-business class exceptions represent problems that are not expected, usually thrown by class libraries, frameworks, or due to their own code logic errors, such as database connection failure, null pointer exception, division by 0 error, and so on.

Business class exceptions must provide two kinds of information:

1. What should the HTTP response status code be if this type of exception is thrown

two。 Text description of the exception

Use a unified exception interceptor at the Controller layer:

1. Set the HTTP response status code: for business class exceptions, use the specified HTTPcode; for non-business class exceptions.

2. Error code of Response Body: exception class name

3. Error description of Response Body: for business class exceptions, use the error text specified by it; for non-business class exceptions, you can unify the copywriting online, such as "server-side error, please try again later". The exception stacktrace is used in the development or test environment, and the server provides the switch for this behavior.

Commonly used http status codes and usage scenarios:

Status code

Working with scen

400 bad request

Commonly used in parameter verification

401 unauthorized

Unauthenticated users, often not logged in. If you still have no permission after verification, it should be 403 (that is, the difference between authentication and authorization).

403 forbidden

No permission

404 not found

Resource does not exist

500 internal server error

Non-business class exception

503 service unavaliable

Thrown by the container, do not throw this exception in your own code

VI. Other

(1) API authentication should use OAuth3.0 framework.

(2) the format of the data returned by the server should use JSON as much as possible, and avoid using XML.

(3) when a more complex interface cannot determine whether to use POST or PUT, it is necessary to look at the specific business layer code to see whether the result generated by the interface is idempotent. If idempotent is used, POST is used instead.

For example, if the interface receives a resource and the resource is updated and no new data is inserted, the interface will use PUT

At this point, I believe you have a deeper understanding of "what are the RESTful specifications of java?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report