Reputation: 48953
I am wanting to build an API first RESTful application in PHP. I have never attempted to do this so I have some questions about how to handle PUT
and DELETE
So for an example if I have a API endpoint that updates a User profile, should I make it accept BOTH a POST
and PUT
Request?
If I was building a Client for my API as a Desktop app or iOS app, etc it would be easy to send a PUT
request to my API but I plan to have a Web based app for my API as well.
So on my web based app, I would have an HTML Form to Update a User profile, this would then be sent as a POST
as HTML Forms do not allow PUT
requests.
Could someone with more experience with this explain the best way to handle my example scenario?
Would the proper way be to send my Form as a POST
to my PHP script, then my PHP script would make a proper PUT
request to my PHP API with cURL?
Upvotes: 0
Views: 1290
Reputation: 158040
I would use GET
POST
PUT
DELETE
as they are described in HTTP. That's restful (in my opinion). As regular browser forms does not support this I would send the data via AJAX.
If you really need to use browser forms, maybe because javascript is not enabled, then using POST
requests with a param like ?method
sounds like a suitable solution - although I don't like it.
Upvotes: 0
Reputation: 99571
You can absolutely also do PUT requests from browsers, but you need javascript.
Generally I would say a good way to think about it, is as follows:
First build a great REST api that follows all the rules. Only once you are at that point, think about the workarounds you need to make it work in other contexts. Submitting an HTML form is a valid thing to need a workaround for.
However, since 'POST' is completely open for interpretation, and has little rules associated, one option would be to create a single resource (or url) on your server that handles all the POST requests coming from browsers. (something like /browserpost
).
You could always add a hidden <input>
field with name="url"
that specifies which resource was actually intended to be updated, and an <input>
with name="method" value="PUT"
for the intention.
You will need to add CSRF protection anyway, so I feel this would be a solid way to deal with this this. 1 endpoint to specifically 'proxy' html-based form submissions and internally do the appropriate mappings to the correct REST services.
Upvotes: 2