Introduction to the REST API. Best practices for designing REST API Rest api description

Golovna / Contacts
The Russian part of the Internet has a large number of articles devoted to web services based on SOAP and XML-RPC, but there is probably nothing about the whole world (or less broadly) REST architecture.

This article describes the basics of this architecture, its possibilities and applications.

What is REST?

REST (Representational state transfer) is a style of software architecture for distributed systems, such as the World Wide Web, which is used to invoke web services. The term REST was coined over 2000 times by Roy Fielding, one of the authors of the HTTP protocol. Systems that support REST are called RESTful systems.

The REST option has a very simple interface for managing information without any additional internal processing. Each piece of information is uniquely identified by a global identifier, such as a URL. Each URL, in its own way, has a strictly task format.

And now, most explicitly:

The presence of additional internal searches means the transfer of data in the same way as the data itself. Tobto. We do not burn data into XML, as do SOAP and XML-RPC, do not use AMF, as do Flash, etc. We just give the data itself.

Each piece of information is uniquely identified by a URL, which means that the URL is the primary key for the piece of information. Tobto. for example, the third book in the police book looks like /book/3, and the 35th page in this book looks like /book/3/page/35. Zvіdsi y exit tasks format. Moreover, it does not matter at all in what format the data is located at the address /book/3/page/35 - it can be HTML, a copy scanned as a jpeg file, or a Microsoft Word document.

How information is managed by the service is entirely based on the transfer protocol. The most advanced protocol is obviously HTTP. So, for HTTP, action on data is determined by the following methods: GET (remove), PUT (add, replace), POST (add, change, delete), DELETE (deleted). Thus, CRUD (Create-Read-Updtae-Delete) operations can be completed using any number of methods, including GET and POST.

The axle is what it looks like on the butt:

GET /book/ - retrieve a list of all existing books
GET /book/3/ - get book number 3
PUT /book/ - add a book (data from the user)

DELETE /book/3 – view the book

IMPORTANT ADDITION: These are called REST-Patterns, which are related to the HTTP methods that need to be broken. Closer to home, different models look at POST and PUT in different ways. However, PUT is not assigned for creation, replay and update, but for POST there is no assignment (The POST operation is very generic and no specific meaning can be attached to it). Therefore, my example will be correct in this form, and as if you mean POST and PUT interchangeably.

Once again, POST can be changed at the same time for all changes:
POST /book/ – add a book (data is requested)
POST /book/3 – change the book (the data will be requested)
POST /book/3 – delete the book (the body will be empty)

This allows you to sometimes ignore unpleasant moments associated with PUT and DELETE problems.

REST wiki for everyday Web services.

As you know, a web service is an add-on that operates on the World Wide Web and access to it is provided via the HTTP protocol, and the exchange of information is in an additional XML format. So, the format of the data that is transferred to the body will always be XML.

For the skin unit of information, 5 actions are indicated. And to yourself:

GET /info/ (Index)- Displays a list of all objects. Call for forgiveness, that's it. Place only the identifier and object name fields, without other data.

GET /info/(id) (View)- Retrieves more information about the object.

PUT /info/ or else POST /info/ (Create)- I’m creating a new object. Data is transmitted in the body without any formal coding, using urlencode. In PHP, the body can be written in this way:

Function getBody() (
if (!isset($HTTP_RAW_POST_DATA))
$HTTP_RAW_POST_DATA = file_get_contents("php://input");
return $HTTP_RAW_POST_DATA;
}

POST /info/(id) or else PUT /info/(id) (Edit)– changes the data with the identifier (id), possibly replacing them. Data is also transmitted in the body of the request, but in the PUT mode there is an important nuance. On the right, the POST request transmits the presence of urldecoded-post-data. Tobto. If you don’t stagnate the code, it doesn’t violate the standard. Here, whoever they want, they don’t show respect for the standard, they vikorist as if they were post-change.

DELETE /info/(id) (Delete)– deletes data from the identifier (id).

Let me point out once again that in our application /info/ - it can be based on any other information that can be (and may be) displayed in the URL:

/data/4/otherdata/6/info/3/ … that’s it.

What you can earn from this concept:

Apparently, the REST architecture is very simple in terms of development. By looking at the prompt, you can tell what it is working without understanding the formats (for SOAP, XML-RPC). Data is transferred without storing additional data, so REST is considered less resource-intensive, since it does not require parsing to understand what is to be done and does not require transferring data from one format to another.

More practical than stagnation.

The main advantage of services is that they can be processed by a system, be it a website, flash, a program, etc. fragments of methods for parsing XML and vykonannya requests for HTTP are present in the near future.

The REST architecture allows you to seriously simplify the task. This is especially true in terms of functionality, but there is little described, and even if it is not possible to give someone the ability to change information, then authorization and authentication are also required. This can easily be done using any other type of session or just HTTP Authentication.

REST API (Representational State Transfer), or RESTful web services, what is it? REST translated from English as “representative transmission to the stan”. This is a method of ensuring interaction between computer systems on the Internet. REST-based web services that allow systems that consume, deny access to text-based web resources and handle them, vikoryst and unified operations. Explore other forms of web services that combine their power with additional sets of operations, such as WSDL and SOAP.

REST API: what is it? I understand

Web resources are primarily identified from the World Wide Web as documents or files identified by their URLs. Today's stench may be more obscure and abstract meaning, which smells the skin object and reality, which can be identified, named, addressed and collected in Merezhi. The REST API web service requests a response in a URI resource, which can be formatted in XML, HTML, JSON, or any other format. You can confirm that changes have been made to the resource that is being saved, as well as push hypertext messages to other related resources and their collections. The use of HTTP, as the most extended protocol, extends to the types of available operations indicated by the commands PUT, DELETE, HTTP GET, POST.

Victory protocols without regulation will become standard operations, REST systems are aimed at high productivity, reliability and availability to increase the number of re-vikoristic components that can be processed and that can be updated without interfering with the system. . REST websites are often simpler and less important in the SOAP (Simple Object Access Protocol) style, while REST networks do not have the same bandwidth costs, making them more suitable for websites on the Internet. For the SOAP approach, you need to write or create a server program (for servicing the data) and a client program (for storing the data).

History of technology

The term “representative transfer to the country” was introduced and coined in 2000 years by Roy Fielding in his dissertation “Architectural styles and design of edge software architectures.” We developed the REST architectural style in parallel with HTTP 1.1 1996-1999, based on the main project HTTP 1.0 1996. In a retrospective look at the development of technology, Fielding said that during the process of HTTP standardization, it was likely to steal design choices on the Internet. This is a very complex process within the framework of the process that accepts propositions from anyone on the topic of how Sweden becomes the center of this galusa.

Feeding comments from more than 500 contributors, many of whom are dedicated engineers with extensive knowledge. It's up to you to explain everything, from the abstract understanding of web interactions to the precise details of HTTP syntax. This process refined this model into a core set of principles, principles and frameworks that are now called REST.

Advantages

The peculiarities of the REST style stem from the following architectural principles:

  • Productivity - the interaction of components and the dominant authorities in the management of productivity and effectiveness measures.
  • Scalability to support the maximum number of components, testing REST APIs and interactions between them.
  • Simplicity of a single interface and authorization REST API.
  • Modification of components to meet specific needs (upon operating programs).
  • Visibility of communication between warehouse and service agents.
  • The ability to port components that move their program code with data.
  • Reliability - high resistance to failure in the event of failures in the warehouse, disconnections or data.

The range of problems between clients is explained by the fact that the REST API allows you to feel the implementation of components, changes the complexity of the semantics of the connector, promotes the efficiency of adjusting productivity and promotes the scalability of pure server components iv. Compact system interconnections allow intermediaries - proxies, gateways and firewalls to communicate at different points without changing the interfaces between components, which allows them to perform REST-transfer or transfer Vati productivity for the help of large-scale zagalny keshuvannya. The application of the REST API is due to the fact that if the interaction does not lie in the form of requests, standard methods and types of media are used to define the semantics and exchange of information, and the results explicitly indicate caching.

Formal and architectural boundaries

Six basic boundaries characterize a RESTful system. They define the ways in which the server can process and receive requests from clients. Acting within the framework of these interactions, the service eliminates the elements of non-functional power, such as productivity, scale, simplicity, abundance, visibility, mobility and reliability. If the service breaks any necessary connections, it cannot be RESTful.

The first boundaries are brought to the client-server architectural style. The reduction of problems to the client interface and the problems of saving data will improve the portability of the client interface on several platforms. It also improves scalability by simplifying server components. Perhaps most significant for Merezha is that it allows components to evolve independently, thereby enabling Internet-scale to large organizational domains.

Safety

REST does not provide any required security support. This is especially important when designing REST web services - security and design needs to be taken into account. REST web services use HTTP PUT and DELETE with CRUD operations. PUT and DELETE are not supported by many browsers and are most often connected to peer servers due to the possibility of compromising confidentiality. If there is no proper setup between the server and the client, any third-party client can create a resource using the PUT method or using a different DELETE resource. During the development period, it was possible to ensure safety for web services and ensure that these moments are protected.

Architectural elements

A key aspect of REST is the nature of its data elements. The REST style has several concepts that describe the behavior and production of information.

Resource is an object (logical or physical) available on the Internet. This could be a document that is stored in the server file system or a row in a database table. The terminal koristuvach interacts with the resource to reach the song mark. To design a system using REST, the designer must think about business objects as resources and those that can be addressed.

URI – uniquely identifies a resource. This parameter changes the address resource and may change. Resources are exchanged for protocol-supported programs such as HTTP.

Podannya - I will become a resource at the moment. The client returns the request to the resource followed by the URI. The resource can be viewed in one or more formats that are transmitted, such as XML, HTML, JSON, RSS, REST API java. These formats can be accommodated with an additional mechanism for content enhancement.

Entitlement - allows the program to cancel the transition from one state to another. Each resource may have connections to other resources. The present may confirm the enactment for the upcoming transition. A well-connected program allows the user to independently open the interface.

Connector

The connection is an abstract interface that mediates connections between components. The fragments of the REST interaction are not deleted, the connector is not responsible for saving information about the network. Therefore, connections between the components can be created in parallel.

The client and server are the main REST connectors. The client initiates the request, and the server processes it.

Cash is another type of roz'em. Caching can be implemented on client, server and other levels. This changes the hour of recovery and the vicinity of the limits.

Components

The components are assembled using strictly defined resource methods, which creates conditions for storage of the production and transfer mill.

User-Agent – ​​a vikoryst client connection for initiating a request.

Origin-server – Vikorist server connector for power supply.

Proxy is an intermediary that is used on the client side to encapsulate the interface with other services. It also includes the translation of data and protection.

A gateway is an intermediary that is installed on the server to ensure encapsulation of the interface by other services.

Prospects for development

Newly relevant food: REST API - what is it for current Internet technologies? REST is the basis of modern web architecture, which is developed by analyzing a few existing styles and introducing new additions to it.

Goals of REST API - what is it? The aim is to combine distinct styles with a coordinated set of boundaries to minimize crosstalk and maximize the independent evolution of components to achieve scale. The price of the new hypermedia architecture. With the advent of smartphones, tablets and gadgets, there is a measure of scale.

RESTful API can be created for third-party services. You can use single-sided robot programs with a back-end. There are a number of key points that you need to know before designing the interface.

URLs and conditions

The key principle of REST is to divide your API into logical resources. Management of these resources is carried out using additional HTTP requests with a standard method – GET, POST, PUT, PATCH, DELETE.

The resource must be described by the name of the multiplicity. Actions over resources are defined using the CRUD strategy and are supported by HTTP methods in the following order:

  • GET /api/users – retrieve the list of clients;
  • GET /api/users/123 - select the specified user;
  • POST /api/users – create a new user;
  • PUT /api/users/123 - update all details of the specified account manager;
  • PATCH /api/users/123 – partly update the data of the koristuvach;
  • DELETE /api/users/123 - vidaliti koristuvach.

Since a resource exists only in the context of another resource, the URL can be combined:

  • GET /api/posts/9/comments - scroll down the list of comments to entry No. 9;
  • GET /api/posts/9/comments/3 - move comment No. 3 to post No. 9.

If the action on an object is a CRUD operation, it can be used as a storage resource:

  • POST /api/posts/9/like - means record No. 9 as similarities;
  • DELETE /api/posts/9/like - remove the “qualified” icon from post No. 9.

The creation and renewal of resources can turn the resource around

The POST, PUT or PATCH methods can change resource fields that were not included before entering (for example, ID, creation date or update date). In order not to overwhelm the user with the API, you need to make another request to remove the updated data, such methods can turn them around.

Filter, sort and search

Any HTTP query parameters can be used in wikis to clarify the query or sort the data.

  • GET /api/users?state=active – list of active account users;
  • GET /api/tasks?state=open&sort=priority,-created_at - a list of uncreated tasks, sorted by priority and creation date (starting with a new task).

Poster navigation

If you need to add information about side navigation to a list of targets, you can quickly use the HTTP Link header rather than adding data wrappers.

Header Butt:

Link: ; rel="next", ; rel="prev", ; rel="first", ; rel="last"

Possible rel values:

  • next – the results page is coming;
  • prev – front side of results;
  • first – first page of results;
  • last – the last side of the results.

It is important to understand these meanings rather than construct different URLs so that sometimes side navigation can be based on complex rules, rather than a simple search of pages.

Reassignment to HTTP method

For use with some servers or clients that do not support HTTP methods other than GET and POST, their emulation may be necessary. The values ​​for the method are passed into the X-HTTP-Method-Override header, and the value itself is labeled as a POST method. GET request is not to blame to change the server camp!

Kodi HTTP status

  • 200 OK – response to a successful request GET, PUT, PATCH or DELETE.
  • 201 Created - the POST response will indicate the result of the creation of a new object. The response may also be accompanied by a Location header, which indicates the URL of the resource.
  • 204 No Content – ​​indicates the successful completion of a command that does not change anything (for example, DELETE).
  • 404 Not Found - the requested object was not found.
  • 500 Internal Server Error – error on the server.

In case of purchases, the type may have additional information for the purchasers, if possible.

Actors say:

"Tse API, which wikirist HTTP request for

GET, PUT, POSTі DELETE ".

Whoever said the same:

“Refer to the additional URI for resource allocation”

Others scream out loud:

At the end you can say:

“In principle, it’s simple API, what a vikorist HTTP Right!"

Acts of these people have confirmed the pardon,

Deyaki chastkovo verni,

but it has no meaning,

Bo stink everyone's missing the point.

To make it possible to develop a RESTful API,

According to the first

What is REST?

What is REST?

REST is:

    Virazno not HTTP

    Chi no protocol

    No specification

Why are there so many REST APIs?

And yet...

REST is a style of architecture.

Oh, wow... what is this style of architecture?

Architecture style

Bazhana architecture

It’s just architecture plus a set of boundaries that build up to architecture, which creates the ultimate architecture.

The zastosovuyuchi and the interconnections are based on the basil architecture, optimized for the underground waterfalls of the vikoristan.

REST stands for data transfer

This was recorded by Roy Fielding in his doctoral dissertation in 2000, describing the current web architecture as an abstraction.

The name of the bula was clicked on Wiklikati about those how to deal with the good development of web supplements.

Roy described REST in a simple example:

Let's take a look at the web pages as a virtual machine.

The skin side represents the body:

1. First, the koristuvach removes the first camp from the appearance of the index camp.

2. Then koristuvach go through the program, selecting the message (here the message is sent to the side)

3. The result of the transfer of the offensive to the Koristuvachevi camp.

REST dosi not HTTP

Of course, as early as 2000, the network was already working on HTTP, and Roy and his fellow engineers were working on it a lot.

However, REST does not specify specific system implementation details or protocol syntax.

It is entirely possible to build a RESTful architecture on top of HTTP-aware protocols.

For example, CoAP (Cooperative Access Protocol) is a RESTful protocol for deploying devices (Internet of Things) and is used to allocate minimal resources both at the device and at the same time.

So what's the point of using REST?

The World Wide Web is based on REST architecture.

Therefore, if you create a non-RESTful API, which is common on the Internet, then you are creating a suboptimal system. Not optimal for optimized architecture.

It is important to note that some non-RESTful APIs may not be optimal for a edge architecture, but not optimal for other problems. For example, modern front-end programs can meet very specific needs, and there is a growing number of data collection libraries, such as GraphQL and Falcor.

So, how many RESTful APIs are there?

The API is RESTful if it consistently operates under REST boundaries.

REST means 6 boundaries to achieve the desired system optimization:

1. Client-server

This exchange is based on the principle of interests.

This allows the components to develop independently. When we create our API, it acts as a server that serves a large number of clients.

2. Without bulk

The connections between the client and the server are seamless. This means that it is the client's responsibility to enter the server with all the necessary information to complete the transaction.

The main advantage of this exchange is that the system can scale more quickly, since the server does not need to save the client's time between requests. The need to remember information about the client's system frees up server resources, so that more clients can be served at the same time.

The most effective measure is the one that does not vikorize the measure.

If we create our API, it is not our fault to ignore the cache.

4. Correct interface

To ensure efficient cache caching, components must be able to communicate through a single interface. With a single interface, desired information can be transmitted in a standard form.

4.1. Identification of resources

This means that any information that can be named can be a resource (image, document, or a set of other resources)

4.2. Manipulation of resources through manifestations

The resource can be represented in different ways.

For example, HTML, XML, JSON or send a JPEG file.

This means that clients interact with resources through their manifestations, which greatly reduces the abstract understanding of resources in their interactions.

4.3 Thirdly, self-described information

This means that the resource can provide descriptions to the reported request, and the server can provide descriptions about the site. Thus, HTTP headers and response codes are the main implementations for this rule.

4.4. Hypermedia may become an engine and become a program

This actually means that the program is equipped with powers that allow clients to access resources through hyper-powering.

As you can see, a lot of rules can be implemented in the HTTP protocol. Therefore, if the Vikorist API uses HTTP correctly, this is a great opportunity to become RESTful.

5. Bagatory system

In a rich network system, intermediaries, such as proxy servers, can be located between the client and the server, using a single-mode network interface.

One of the advantages of the rich system is that intermediaries can intercept client-server traffic for song purposes/for example, for caching.

6. Vimoga code

This uncomplicated exchange allows clients to install programs for logging on the client’s side. The best example for this is JavaScript interface add-ons. This may be immediately obvious to us, but in the early days of the Internet there was a concept that was evolving, and this was a core part of Internet architecture.

So, how to create a REST API?

Properly vikoristuvat HTTP

If you want a RESTful API, vikorize the RESTful protocol. For the Internet, the HTTP protocol is the first choice. Create an API for proper HTTP usage.

Create a single interface

Align your concepts with resources and assign unique identifiers to each of them. The simplest way would be to use a database service for foreigners. For such a service we can name two resources; Koristuvachiv and koristuvachiv (collection resource). These resources can be identified by the /users URI and the /user/(id) URI of your API.

Showcase your API hyperpowers

Remember the REST architecture

The less challenging aspect of creating a RESTful API comes down to how important it is to understand the Internet and its underlying architecture. We can either speed up this optimization, or we can ignore it.

If you have any food problems, we request our

Thank you for reading my post.
The backlash and thoughts are always floating around in the comments section.

Hello, dear readers! Before you start reading this article, I would like to describe the goals of this creation and revelation that prompted me to write it.

On one of the projects of our company, Vinyl, there was a need to design a server application in the REST style. From the very beginning we wondered what to do with a simple task and for this purpose to extract the most powerful information.

Once we started the process of developing the architecture and bringing REST services to a unified style, our colleagues and I began to have conflicting issues and different points of view on the implementation of this or that aspect. Here we realized that it is necessary to open Google and go to the aid of the collective mind, learn the best practices that need to be avoided when designing RESTful programs.

This article will be of interest to those people who may already have a clear understanding of working with web add-ons (and possibly with REST services), but will not require consolidation and standardization of their knowledge.

Viznachennya

To begin with, you need to figure out what REST is. Wikipedia gives this nutritional answer. REST (Representational State Transfer- “Transfer to the manifestation”) is an architectural style of interaction between the components of a divided appendage within a boundary. REST provides a convenient set of connections to be considered when designing a distributed hypermedia system.

In my own words, I explained the concept of REST as “a set of recommendations that allows you to unify the interaction between client and server applications.”
In this article, I will try to inform you about these “recommendations” that will help you design and create REST services in accordance with generally accepted practices.

Also understand that this is a REST service. I defined the REST service as “the point of interaction between the client program and the server.” In Java terminology, this is a servlet, which client sends the request.

Issues

Before we begin to describe the rules, I would like to convey the idea that REST is not a standard, because there are no uniform rules that need to be followed. This means that there is still no greater understanding of those solutions that can best resolve one situation or another. It’s very common to read about what HTTP methods to use and what HTTP code to use in each specific situation.

Service name

To get started, you need to select a name for the REST service. Under the name of the service, I respect your path in the URI of the request. For example, http://my-site.by/api/rest/service/name. To choose a name, we need to understand what “resources” are in REST architecture.

Submission to the resource

In REST terminology, it can be a resource - an HTML document, images, information about a specific client, etc. Since a resource is a real object, it is easy to see in a standard format, for example, XML or JSON. Then the server can send this resource using the selected format, and the client can work with the resource using the selected format from the server.

Example submitted to the "profile" resource in JSON format:

    "id" :1 ,

    "name" :"Mahesh" ,

    "login" :"manesh"

REST does not impose any explicit restrictions on the format that will be used for representing resources, and there are few rules that must be followed when developing a format that will be used to represent resources:

  • The client and server are responsible for understanding and being able to work with the selected format.
  • The resource can be completely described in any chosen format, regardless of the complexity of the resource.
  • The format can convey the possibility of making connections between resources.

An example of a submission to the resource “request” and a connection with the resource “profile”:

    id: 11254,

    currency: "EUR" ,

    amount: 100

    profile: (

    id: 11,

    uri: "http://MyService/Profiles/11"

As you can see, it is not obligatory to duplicate the entire structure of a resource that is assigned to another resource. Natomist can be vikoristovat reasonable sending to another resource.

Zvernennya to resource

The skin resource may be uniquely identified by a permanent identifier. "Permanent" means that the identifier does not change during the hour of data exchange, and when it changes, it will be assigned to the resource. If the resource is assigned a different identifier, the server is required to notify the client, which will then indicate the date of sending to the new address. A resource is uniquely identified by a URL. This means that the URL is the primary key for the data item. Totto, for example, another book from the book police matima looked /books/2 , and the 41st side of this book is /books/2/pages/41 . Zvіdsi y exit tasks format. Moreover, it does not matter at all which format contains the data behind the address /books/2/pages/41 – This can be HTML, a scanned copy of a jpeg file, or a Word document.

It is recommended to select multiple resource names when assigning a name to a REST service. This approach allows you to add new REST services without expanding the names of the existing ones. For example, service /books give us a list of all your books, /books/3 turn to the information about the 3rd book, and the service /books/3/pages turn all the sides of the third book.

For services that create specific actions on a resource, there are two approaches for entering actions: in the service name or in its parameters. For example, /books/3/clean or /books/3?clean . I give preference to the first option, because such services often use POST methods that do not support passing parameters to the URL, which makes the service, in my opinion, not very readable. Due to the importance of the type of action in the name of the service, we will expand our service more, as much as possible lies in the type of HTTP method.

It is also not recommended to use names that include a tag on the left and describe the business of the warehouse service (as it is recommended to work when naming java methods). For example, zamіst /getAllCars a better way to earn money /cars . Since the method cannot be described in one word, it is necessary to establish a single style of separators, I call the vikory '-', which is the most popular approach. For example, /cars/3/can-sold.

More details about the design of REST service names can be read in

HTTP method

REST has 4 main HTTP methods: GET, POST, PUT, DELETE. Most often, the skin of the methods will serve until the end of the business with CRUD ( c reate, r ead, u pdate, d elete – “creation, reading, updating, viewing”).
POST – create, GET – read, PUT – update, DELETE – delete.

IMPORTANT ADDITION: These are called REST-Patterns, which are related to the HTTP methods that need to be implemented. Closer to home, different models look at POST and PUT in different ways. However, PUT assignments for creation, replacement or updating are not assigned for POST. Therefore, the POST and PUT codes can be interchanged. In most cases, POST is used for creation, and PUT is used for editing, and I’ll explain why a little later.

I will provide a number of examples of various methods of interaction with resources.

  • GET /books/- Selects a list of all books. Call for forgiveness, that's it. Place only the identifier and object name fields, without other data.
  • GET /books/(id)- Removing more information about the book.
  • POST /books/- I’m creating a new book. Data is transmitted in a note.
    PUT /books/(id)– changes data about the book with identifier (id), possibly replacing them. Data is also transmitted at the request.
  • OPTIONS /books- Selects the list of supported operations for the assigned resource (practically not vicorized)
  • DELETE /books/(id)– deletes data from the identifier (id).

Security and idempotency

It will also help you choose an HTTP method to know the security and idempotency of these methods.

A careless request is not a request that does not change the status of the program.

An idempotent request is not a request, the effect of which is a multi-response derivation is older than the effect of a disposable derivation.

Judging by this table, the GET request does not change the status of the resource that is being stagnated. PUT and DELETE statements can change the status of the resource, but they can be calmly repeated, since there is no reason that the previous statement has ended. In principle, it is logical: if you repeatedly repeat a particular resource and replace it with a given resource, the result will be a further replacement of the resource. Ale POST is written, as seen in the table, not secure and indempotent. Not only does it change the resource, but also the effect that is often repeated is highly variable. This is instead represented by the operation of adding new DB elements: the window is written X times, and the DB has received X elements.

I’ll also point out why GET requests are not to blame for changing the status of the resource. GET requests can be cached, for example, on a proxy server. In this case, the request may not reach the server by the program, but because the proxy server returns the information from the cache.

HTTP codey

The HTTP standard describes over 70 status codes. In good form, I would like the main ones.

  • 200 – OK – successful request. If the client has requested any data, it will appear in the header and/or information.
  • 201 – OK – as a result of a successful quest, a new resource has been created.
  • 204 – OK – the resource was successfully acquired.
  • 304 – Not Modified – the client can access data from the cache.
  • 400 – Bad Request – the request is invalid or the request cannot be processed.
  • 401 – Unauthorized – the request indicates the authentication of the customer.
  • 403 – Forbidden – the server has requested permission, but is not allowed to process it and access is blocked.
  • 404 – Not found – resource not found.
  • 500 – Internal Server Error – API developers are guilty of avoiding such bugs.

These benefits may be caught in the global catch block, pledged, or otherwise turned back from the branch.

The larger the set of codes that we will vikorize, the more intelligent will be the API that we create. However, be aware that browsers process these codes differently. For example, some browsers that reject the 307 response code immediately display a redirect, and some allow you to handle this situation and save the action. First of all, it is important to understand how it works on the client side!

Headers

  • Content-Type- Asked format;
  • Accept- List of broadcast formats.

Parameters for searching resources

In order to simplify the selection of services that are responsible for processing any information, and also make them more productive, it is necessary to understand how to enter parameters for sorting, filtering, etc. forest of fields and pagination.

Filtration

Create a unique parameter for the skin field for filtration. This allows you to limit the amount of information that is output, which optimizes the processing time of the request.

For example, to display all the red books, you need to write:

GET /books?color=red

Sortuvannya

Sorting is implemented in a similar way to filtration. For example, to display all the books sorted by publication by date and by title by growth, you need to enter the following entry:

GET /books?sort=-year,+name

Pagination

In order to support the possibility of accessing a list of resources that may appear on the same page of the program, the REST API uses pagination functionality. It is implemented using the SQL parameters known to us: limit and offset. For example:

GET /books?offset=10&limit=5

In addition, it is good form to display a message on the front, back, first and remaining pages in the Link header. For example:

Link: ; rel="next",
; rel="last",
; rel="first",
; rel="prev"

Select fields for resource

For a manual service, to save traffic, you can add the ability to customize the data display format. It is possible to select fields for the resource, which may update the REST service. For example, if you need to remove both book ids and their colors, you need to enter the next entry:

GET /books?fields=id,color

I'll save you

One of the reasons for the exchange of RESTful services is that they have to save the client’s time, in order to remove requests.

An example to the service that does not save money:
Request1:
Request2: GET http://MyService/Persons/2 HTTP/1.1

The skin from these drinks may develop skin problems regardless of the other.

An example of a service that saves money:
Request1: GET http://MyService/Persons/1 HTTP/1.1
Request2: GET http://MyService/NextPerson HTTP/1.1

To process another request, the server needs to “remember” the id of the remaining person that the client requested. Tobto. The server is responsible for “memorizing” its production line, otherwise another supply may cause problems. When designing a service, there is no need to save energy, leaving a low priority.

Advantages of the service, which does not save the cost:

  • the service asks for drinks independently of each other;
  • the architecture of the service will say goodbye;
  • No additional effort is required to implement services using the HTTP protocol, which also does not save data.

Not enough service that does not save money:

  • The client himself is responsible for transferring the context-needed service to the service.

Version

It is good practice to support the REST API version. This allows you to easily expand the API without obliging clients who are already using it to make changes.
A number of approaches to implementing versioning:

  • For further assistance, Accept the header. In this case, the API version is specified in Accept - Accept:text/v2+json
  • Z wikiristannyam URI. In this approach, the API version is specified directly in the URI - http://localhost/api/v2/books
  • Custom header wiki. You can use the power header, which is also responsible for passing the API version - API-Version:v2
  • Vikoristannya parameter is asked. You can use the API version transfer parameter - /books?v=2

Each of the presented methods has the right to sleep, each has its own pros and cons. However, it is up to you to decide which method of implementing version control will suit your project.

Documentation

To manually configure our REST services, you need to create good and comprehensive documentation. For this you can use different tools, for example, Mashape or Apiary, but I recommend using Swagger.

Swagger is a technology that allows you to document REST services. Swagger encourages faceless programming and frameworks. Plus Swagger provides a UI for reviewing documentation.

You can view the report information about Swagger for a price.

Archive

Keshuvannya

Also, to speed up requests to the database and increase the speed of data for our REST services, it is recommended to set the caching mechanism. Caching can be adjusted both on the server level and, in addition, depending on the situation.

Keshuvannyam can use the following HTTP headers:

  • Date - date and hour of creation of the resource.
  • Last Modified – date and hour of the last change to the resource on the server.
  • Cache-Control is an HTTP 1.1 header that is used to control caches.
  • Age - the hour after the moment of the remaining capture of the resource, the header can be added by the intermediate (between the client and the server) component (for example, a proxy server)

© 2024 androidas.ru - All about Android