HTTP Methods with RESTful API

Source: Internet
Author: User
Tags http post representational state transfer

Directory:

    1. What is RESTful?
    2. Json-server (provides RESTful API interface + JSON return data)
    3. How to choose a REST method
    4. HTTP Verbs/method (Security | idempotent)
    5. HTTP POST v.s. PUT
    6. REST POST | PUT | PATCH

  • What is restful Nanyi: Understanding RESTful architecture

    • Representational state Transfer characterization Status shift
    • Core: Resource. Representation refers to the expression layer of resource.
      Resource, a resource, an entity (text/image/service) that can be uniquely identified with a URI.
    • Representation, Presentation layer
      A resource is an entity that can have a variety of external representations. This form of expression, that is, the representation presentation layer.
      e.g. text can be expressed in txt or with Html/xml/json.
    • State Transfer, Status shift
      Client <-> Server, this interaction involves changes in data and state.
      Client Operations server, that is, by means of a method (HTTP method), causes the server to take place in a state transition.

    • Current understanding of REST: (2016-8-20)

      • Each URI represents a resource. Use a noun to express.
      • The HTTP method indicates what type of operation was performed on the resource.
    • HTTP verbs recommended Status codes returned

    • TOP10 HTTP Status Code in REST
      • 200 OK201 Created204 No Content
      • 304 Not Modified
      • 400 Bad Request401 Unauthorized 403 Forbidden 404 Not Found409 Conflict
      • 500 Internal Server Error
    • The water is deep, and I can't understand it now.
      • Richardson Maturity Model
        1. Level 1-resources
        2. Level 2-http Verbs
        3. Level 3-hypermedia Controls
      • Fielding ' s paper
      • Learn Rest:a RESTful Tutorial
      • What exactly is RESTful programming?

Json-server

  • The Json-server is a front-end test tool that provides REST API + JSON services.
  • Look at a set of RESTful API interfaces provided by Json-server:

    GET   /posts    //获取posts下的所有资源GET   /posts/1  //获取posts下id为1的资源GET   /posts?title=json-server&author=typicode //获取posts下title=json-server&author=typicode的资源POST  /posts   //posts添加操作PUT   /posts/1 //对posts下id为1的资源进行修改操作:完全替换PATCH /posts/1 //对posts下id为1的资源进行修改操作:局部更新DELETE   /posts/1  //对posts下id为1的资源进行删除操作
  • There are two obvious features:
    • Each URI represents a resource. Use a noun to express.
    • The HTTP method indicates what type of operation was performed on the resource.
  • When using, be aware that:

    • get
      Use & to stitch query parameters into query strings

       if  (Data && Object.prototype.toString.call (data) = = "[Object Object]"  { for  (var  i in   data) {Datastr  + = i + "=" + Data[i] + "&" ; }}lastpos  = Datastr.lastindexof ("&" );d Atastr  = Datastr.slice (0, Lastpos); 

       

    • In the post put patch request, the value of the Content-type must beapplication/json
      Corresponding, need to submit the data, by the JS object--JSON json.stringify ()

      Xhr.setrequestheader ("Content-type", "Application/json"null);

  • RESTful

    RESTful is just a architectural style, meaning that if everyone does this, communication costs will be low and development efficiency will be high.

    So as long as the front and back of the contract is good, you can choose the method freely?

    This is wrong because a request passes through many intermediaries and middleware applications WHI CH perform optimizations based on the HTTP method type. These optimizations depend on key characteristics of HTTP methods:idempotency and safety, which is defined in the HT TP specification.
    Code ahoy:rest design-choosing the right HTTP Method

    From this perspective, which method is used for which operation depends on the properties of the HTTP method itself and the conventions of the front and back interactive interfaces .

  • Two key features of the HTTP method: 安全 | 幂等 ( safe | idempotent

    • safe
      Safe methods are expected to not produce any side effects (side effects). These operations are read-only. e.g. querying the database.
    • idempotent
      The Idempotent method ensures that a request is repeated with the same effect as one request. (It does not mean that the response returned to the client is always the same; it means that the state of the resource on the server is not changed since the first request)
      In mathematics, idempotent refers to the same result of N-times transformation and one-time transformation.

      x = 1;    /* 幂等 */x++;      /* 非幂等 */

  • 安全|幂等 is a contract defined by the HTTP standard: developers must adhere to the RESTful API when implementing it.

    • If an operation is not implemented in a idempotent manner, it will not automatically become idempotent/secure even if it is called by the GET method.
    • When building a RESTful program using HTTP, the implementation of HTTP method should satisfy its security and idempotent, so that the client and middleware can be freely optimized by contract and enhance the user experience.

      e.g. the browser does not know exactly what a particular form is intended for, but if the form is submitted via HTTP GET, the browser will know that when a network exception occurs, it can safely and automatically retry the commit. The form submitted via HTTP POST is not secure if the browser repeats the submission without first confirming it to the user.

  • Under a post put RESTfulpatch

    • post

      • Non-idempotent: two times the same post request creates two copies of the resources on the server side, which have different URIs.
      • The URI corresponding to the POST is not the resource itself, but the recipient of the resource. For example, the semantics of post xx/articles is to create a post under Xx/articles.
      • How does POST design an interface for an order from another perspective? post /orders ?

        The POST was originally designed to commit transactional operations such as forms. So POST can be understood as executing a transaction on the server. The POST request server performs an action, and multiple initiating requests can cause the action to execute multiple times: non-idempotent.

    • put
      • Idempotent: The side effects of multiple put on the same URI are the same as the one put.
      • The URI for the PUT is the resource itself to be created or updated. For example, the semantics of PUT xx/articles/4231 is to create or update a post with ID 4231.
    • patch
      • Non-idempotent e.g. patch you can make incremental changes to a resource in a logical sense, such as adding 3 at a time, and performing multiple times will have additional impact.
      • A partial update to an existing resource (without specifying the entire resource).
    • Some people think that you should use POST to create new resources, and put to update existing resources. If you do the update with POST, it doesn't fit in RESTful style.

    • This is not actually the case.

      The REST standard doesn ' t stop us from using POST requests for updates. In fact, it doesn ' t even talk about it because idempotency and safety guarantees is properties of the HTTP protocol, not of the REST standard.

      The author Code Ahoy also quoted Roy Fielding's words to the effect that, for example, RESTful does not use get for unsafe operations because it violates the definition of Get methods in HTTP, which in turn affects middleware and search engines. The method defined by HTTP is part of the WEB's architecture definition and does not belong to the REST architecture style.

    • Therefore, the use of POST or PUT is due to: the idempotent guarantee of these methods.

    • Because put is idempotent, clients or middleware can send a put request repeatedly when the response of the first request does not arrive in time, regardless of whether the server has already processed the first request. To ensure idempotent, PUT requests must replace the entire resource, so all attributes must be sent. If you want to make a partial update, you must use POST or PUT these non-idempotent methods.

  • Since the choice of POST or PUT is not part of the REST architecture style, but the design of HTTP, let's take a look at what the two are applied to in HTTP respectively.
  • POST v.s. PUT in HTTP

    The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-uri. The URI in a POST request identifies the resource, that would handle the enclosed entity. That resource might is a data-accepting process, a gateway to some other protocol, or a separate entity that accepts Annot Ations. In contrast, the URI of a PUT request identifies the entity enclosed with the Request–the user agent knows what URI is I Ntended and the server must not attempt to apply the request to some other resource. Method Definitions RFC2616

    • The most fundamental difference between POST and PUT is reflected in the meaning of the request URI:

      • The URI in the POST request that identifies the resource to process the attached entity.
      • The URI of the PUT request, which identifies the attached entity.
    • PUT

      PUT puts a file or resource at a specific URI, and exactly at the that URI.

      If the resource is already in the location specified by this URI, the put replaces the resource, and if not, the put creates one.
      However, the response to the PUT request is not cached.

    • POST

      POST sends data to a specific URI and expects the resource at that URI to handle the request.

      The response to the POST request is cacheable, as long as the server has the appropriate Cache-control and Expires headers set up.

      The HTTP RFC specifies that POST is used to:

      • Annotation of existing resources;
      • Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
      • Providing a block of data, such as the result of submitting a form, to a data-handling process;
      • Extending a database through an append operation.
    • One of the benefits of using REST is that it facilitates the correct use of HTTP verbs/methods.

    • What ' s the difference between a POST and a PUT HTTP REQUEST?
  • Finally, to summarize:

    POST to a URL creates a child resource at a server defined URL.
    PUT to a URL creates/replaces the resource in its entirety at the client defined URL.
    PATCH to a URL for updates part of the resource at the client defined URL.

      • postput

        Created object whose URL is named by client or server? Server decision- post ; client naming- put .

        If you only know the URL of the parent category of this resource, use post ; (for example, create a resource ID that is self-growing in the database);

        POST /expense-report

        In other words, if you know the URL of the resource that will be created, use put ;

        PUT  /expense-report/10929

        putis a candidate for creation: When the client knows its URL before the resource is created.

      • putpatch

        • putUsed to completely replace a known resource, requiring the front end to provide a complete resource object, and the missing field is emptied.
        • patchTo do a partial update, the background will only update the received fields. "Save Bandwidth"
      • Ref
        • PUT vs POST in REST
        • REST design-choosing the right HTTP Method

HTTP Methods with RESTful API

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.