When to use PUT vs POST while calling APIs?

  softwareengineering

GIST:

PUT is idempotent PUT is used for updating/creating a resource.

POST isn’t idempotent. POST is used for creating a resource.

So, I’m wondering what should I use in this case and why?

I want to send firebase cloud message notification (FCM). Should I use PUT or POST request? What’d happen if I use PUT or POST? Below is a sample POST request.

curl -X POST 
https://fcm.googleapis.com/fcm/send 
  -H 'authorization:##auth_key##' 
  -H 'cache-control: no-cache' 
  -H 'content-type: application/json' 
  -H 'content_available: true' 
  -H 'priority: high' 
  -d '{
    "notification": {
        "body": "body curl",
        "title": "title curl"
    },
    "to" : "##gcm_reg_id##"
}'

3

I’m wondering what should I use in this case and why?

As a REST client – you do what the server tells you to do. That’s a consequence of the REST hypermedia constraint. If you think about how web forms work – the reason that a browser can distinguish a GET form from a POST form is that we have commonly understood semantics for describing the distinction.

You should not expect useful results to occur when you try to guess what messages to send to a web server.

But in general, you would expect to use PUT when what you are doing is “remote authoring”; analogous to either (a) adding a new page to a web server or (b) replacing an old version of a web page with an updated version.

Note that both of the cases require that the client knows the URI for the targeted resource in advance.

For almost everything else (including the above cases where the client does not know the URI in advance), it is okay to use POST.

If the developers of the API are being especially conscientious, you might be able to obtain more information by sending an OPTIONS request, thereby discovering which HTTP methods are supported via the Allow header in the response.

0

LEAVE A COMMENT