• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

REST API Tutorial

  • REST
  • JSON
  • Dark Mode
Home / Resources / HTTP Methods

HTTP Methods

REST APIs enable you to develop any kind of web application having all possible CRUD (create, retrieve, update, delete) operations. REST guidelines suggest using a specific HTTP method on a particular type of call made to the server (though technically it is possible to violate this guideline, yet it is highly discouraged).

Use below-given information to find a suitable HTTP method for the action performed by API.

Table of Contents

HTTP GET
HTTP POST
HTTP PUT
HTTP DELETE
HTTP PATCH
Summary
Glossary

HTTP GET

Use GET requests to retrieve resource representation/information only – and not to modify it in any way. As GET requests do not change the state of the resource, these are said to be safe methods. Additionally, GET APIs should be idempotent, which means that making multiple identical requests must produce the same result every time until another API (POST or PUT) has changed the state of the resource on the server.

If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process.

For any given HTTP GET API, if the resource is found on the server, then it must return HTTP response code 200 (OK) – along with the response body, which is usually either XML or JSON content (due to their platform-independent nature).

In case resource is NOT found on server then it must return HTTP response code 404 (NOT FOUND). Similarly, if it is determined that GET request itself is not correctly formed then server will return HTTP response code 400 (BAD REQUEST).

Example request URIs

  • HTTP GET http://www.appdomain.com/users
  • HTTP GET http://www.appdomain.com/users?size=20&page=5
  • HTTP GET http://www.appdomain.com/users/123
  • HTTP GET http://www.appdomain.com/users/123/address

HTTP POST

Use POST APIs to create new subordinate resources, e.g., a file is subordinate to a directory containing it or a row is subordinate to a database table. When talking strictly in terms of REST, POST methods are used to create a new resource into the collection of resources.

Ideally, if a resource has been created on the origin server, the response SHOULD be HTTP response code 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header.

Many times, the action performed by the POST method might not result in a resource that can be identified by a URI. In this case, either HTTP response code 200 (OK) or 204 (No Content) is the appropriate response status.

Responses to this method are not cacheable, unless the response includes appropriate Cache-Control or Expires header fields.

Please note that POST is neither safe nor idempotent, and invoking two identical POST requests will result in two different resources containing the same information (except resource ids).

Example request URIs

  • HTTP POST http://www.appdomain.com/users
  • HTTP POST http://www.appdomain.com/users/123/accounts

HTTP PUT

Use PUT APIs primarily to update existing resource (if the resource does not exist, then API may decide to create a new resource or not). If a new resource has been created by the PUT API, the origin server MUST inform the user agent via the HTTP response code 201 (Created) response and if an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request.

If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.

The difference between the POST and PUT APIs can be observed in request URIs. POST requests are made on resource collections, whereas PUT requests are made on a single resource.

Example request URIs

  • HTTP PUT http://www.appdomain.com/users/123
  • HTTP PUT http://www.appdomain.com/users/123/accounts/456

HTTP DELETE

As the name applies, DELETE APIs are used to delete resources (identified by the Request-URI).

A successful response of DELETE requests SHOULD be HTTP response code 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has been queued, or 204 (No Content) if the action has been performed but the response does not include an entity.

DELETE operations are idempotent. If you DELETE a resource, it’s removed from the collection of resources. Repeatedly calling DELETE API on that resource will not change the outcome – however, calling DELETE on a resource a second time will return a 404 (NOT FOUND) since it was already removed. Some may argue that it makes the DELETE method non-idempotent. It’s a matter of discussion and personal opinion.

If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.

Example request URIs

  • HTTP DELETE http://www.appdomain.com/users/123
  • HTTP DELETE http://www.appdomain.com/users/123/accounts/456

HTTP PATCH

HTTP PATCH requests are to make partial update on a resource. If you see PUT requests also modify a resource entity, so to make more clear – PATCH method is the correct choice for partially updating an existing resource, and PUT should only be used if you’re replacing a resource in its entirety.

Please note that there are some challenges if you decide to use PATCH APIs in your application:

  • Support for PATCH in browsers, servers, and web application frameworks is not universal. IE8, PHP, Tomcat, Django, and lots of other software has missing or broken support for it.
  • Request payload of a PATCH request is not straightforward as it is for PUT request. e.g.

    HTTP GET /users/1

    produces below response:

    {id: 1, username: 'admin', email: '[email protected]'}

    A sample patch request to update the email will be like this:

    HTTP PATCH /users/1

    [
    { “op”: “replace”, “path”: “/email”, “value”: “[email protected]” }
    ]

There may be following possible operations are per the HTTP specification.

[
{ "op": "test", "path": "/a/b/c", "value": "foo" },
{ "op": "remove", "path": "/a/b/c" },
{ "op": "add", "path": "/a/b/c", "value": [ "foo", "bar" ] },
{ "op": "replace", "path": "/a/b/c", "value": 42 },
{ "op": "move", "from": "/a/b/c", "path": "/a/b/d" },
{ "op": "copy", "from": "/a/b/d", "path": "/a/b/e" }
]

The PATCH method is not a replacement for the POST or PUT methods. It applies a delta (diff) rather than replacing the entire resource.

Summary of HTTP Methods for RESTful APIs

The below table summarises the use of HTTP methods discussed above.

HTTP MethodCRUDEntire Collection (e.g. /users)Specific Item (e.g. /users/123)
POSTCreate201 (Created), ‘Location’ header with link to /users/{id} containing new ID.Avoid using POST on single resource
GETRead200 (OK), list of users. Use pagination, sorting and filtering to navigate big lists.200 (OK), single user. 404 (Not Found), if ID not found or invalid.
PUTUpdate/Replace405 (Method not allowed), unless you want to update every resource in the entire collection of resource.200 (OK) or 204 (No Content). Use 404 (Not Found), if ID not found or invalid.
PATCHPartial Update/Modify405 (Method not allowed), unless you want to modify the collection itself.200 (OK) or 204 (No Content). Use 404 (Not Found), if ID not found or invalid.
DELETEDelete405 (Method not allowed), unless you want to delete the whole collection — use with caution.200 (OK). 404 (Not Found), if ID not found or invalid.

Glossary

Safe Methods

As per HTTP specification, the GET and HEAD methods should be used only for retrieval of resource representations – and they do not update/delete the resource on the server. Both methods are said to be considered “safe“.

This allows user agents to represent other methods, such as POST, PUT and DELETE, in a unique way so that the user is made aware of the fact that a possibly unsafe action is being requested – and they can update/delete the resource on server and so should be used carefully.

Idempotent Methods

The term idempotent is used more comprehensively to describe an operation that will produce the same results if executed once or multiple times. Idempotence is a handy property in many situations, as it means that an operation can be repeated or retried as often as necessary without causing unintended effects. With non-idempotent operations, the algorithm may have to keep track of whether the operation was already performed or not.

In HTTP specification, The methods GET, HEAD, PUT and DELETE are declared idempotent methods. Other methods OPTIONS and TRACE SHOULD NOT have side effects, so both are also inherently idempotent.

References:

https://www.w3.org/Protocols/rfc2616/rfc2616.txt
http://tools.ietf.org/html/rfc6902
https://en.wikipedia.org/wiki/Idempotence#Computer_science_meaning

Was this article helpful?

Share this:

  • Twitter
  • Facebook
Previous Tutorial:
Richardson Maturity Model
Next Tutorial:
Comparing SOAP vs REST APIs

Reader Interactions

Comments

  1. Moritz Friedrich says

    February 11, 2020 at 12:33 pm

    Returning a 404 for unsupported actions is definitely wrong, that’s what the status code 405: Method not allowed is for. The PUT/PATCH/DELETE on /users you listed should all return a 405 instead of a 404. This might seem like nitpicking, but I think this website strives for correct content.

    Reply
    • Admin says

      February 11, 2020 at 5:02 pm

      Thank you for your feedback. You are right. I updated the post.

      Reply
  2. Philip Patrick says

    November 20, 2019 at 8:14 pm

    What about Merge Patch: https://tools.ietf.org/html/rfc7396? It simplifies patching and makes the process less painful than the original PATCH specification.

    Reply
  3. Adam says

    August 9, 2019 at 9:59 am

    I have a service that validates entries for a sport. It can accept multiple entries, and each entry contains the id of the entrant and other details of the entry, all wrapped up in a JSON list of objects.
    Validation doesn’t change anything – it just checks the data and returns response – is the entry valid, and if not, why not.
    The service is most definitely idempotent – you can call it again and again without anything changing.

    So, it should be GET, but GET doesn’t allow for a payload like POST does – and it is POST I use for this purpose.

    These verbs may well have made sense when the web started, but since the advent of Web services and API’s, which provide complex responses to complex data, but don’t make changes, there is a gap in the described functionality.

    Maybe we need to extend ‘GET’ to allow for a payload?

    Reply
    • Admin says

      August 9, 2019 at 4:31 pm

      Thanks for sharing your thoughts. Yes, theory sometimes does not fit in real world.

      Reply
    • Darren Woodford says

      August 20, 2019 at 12:21 pm

      Some implementations will allow payload in GET but it certainly isn’t standard and I would avoid it where possible. Nothing wrong with overloading POST where it doesn’t fit the REST definition. Remember POST and GET were all we had once upon a time. Having said that if the payload isn’t too crazy you could try passing it as query params.

      Reply
    • Duncan says

      November 14, 2019 at 11:08 am

      Have you tried using query parameters?

      GET weburl.com/validate?id=1&id=3&id=4

      or GET weburl.com/validate?id=1,2,3,4,5,221
      or even GET weburl.com/validate?id_in=1,2,3&id_get=220 (where id_get means ids greater or equal to)

      How you parse the query parameters is up to you – any of these options should work.

      The only key consideration is the 2048 character url name limit.

      Reply
      • BALAGANESH MOHANAVEL says

        November 28, 2019 at 4:00 pm

        Problem is that if we dynamically pass query parameter values with special characters, no solution at all.
        Since URL encoding doesnt work in this case.
        Currently am searching for solution to this case. I dont know the special char will come in my dynamic data from flow and its location.
        e.g taskname = ‘RED & BLUE “. How can I dynamially encode this to RED%26%BLUE in runtime?

        Reply
        • Michal Vašut says

          January 31, 2020 at 12:54 pm

          https://www.php.net/manual/en/function.urlencode.php

          https://www.w3schools.com/jsref/jsref_encodeuri.asp

          Reply
  4. Wafa says

    July 8, 2019 at 1:34 pm

    I want to Create a Task list on sharepoint by HTTP Request how can I establish that?

    Reply
  5. Shahid Dar says

    April 17, 2019 at 7:40 am

    What actually Does it mean?
    Avoid using POST on single resource

    Reply
    • Admin says

      April 17, 2019 at 8:24 am

      Please refer to example URIs in POST explanation above.

      Reply
    • Darren Woodford says

      August 20, 2019 at 12:18 pm

      “What actually Does it mean?
      Avoid using POST on single resource”
      It means you don’t include an id in the URl when using POST method.

      Reply
  6. Keshav says

    March 6, 2019 at 1:32 pm

    I have a query on GET /users (collection resource)
    1) If Database Table has data
    2) If Database Table doesn’t have data

    what should return response and status code? is empty [] with 200 status code or 404?

    Please provide some clarity.

    Reply
    • Admin says

      March 8, 2019 at 5:26 pm

      I will suggest to return empty collection with response code 200.

      Reply
      • masquinyo says

        June 29, 2019 at 1:05 pm

        Is better to just return a response code of 204 – No Content since it is telling the client the resource has no content related to the request.

        Reply

Leave a Reply to BALAGANESH MOHANAVEL Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Search Tutorials

Learn REST

  • What is REST?
  • REST Constraints
  • REST Resource Naming Guide

Guides

  • Caching
  • Compression
  • Content Negotiation
  • HATEOAS
  • Idempotence
  • Security Essentials
  • Versioning
  • Statelessness in REST APIs

Tech – How To

  • REST API Design Tutorial
  • Create REST APIs with JAX-RS

FAQs

  • PUT vs POST
  • N+1 Problem
  • ‘q’ Parameter

Resources

  • What is an API?
  • Comparing SOAP vs REST APIs
  • HTTP Methods
  • Richardson Maturity Model
  • HTTP Response Codes
    • 200 (OK)
    • 201 (Created)
    • 202 (Accepted)
    • 204 (No Content)
    • 301 (Moved Permanently)

Footer

References

  • The dissertation by Roy Thomas Fielding
  • Uniform Resource Identifier (URI, URL, URN) [RFC 3986]
  • Internet MediaTypes
  • Web Application Description Language (WADL)

Meta Links

  • About
  • Contact Us
  • Privacy Policy

Blogs

  • How To Do In Java

Copyright © 2020 · restfulapi.net · All Rights Reserved. | Sitemap