I'm building API with the following structure:
- method
POST
- uri
/words
. - body
{"word":"example"}
.
This request should add word to database and if I testing it by httpie
everything is ok.
$ http POST localhost:8000/words word="new word2"
HTTP/1.1 200 OK
Access-Control-Allow-Headers: application/json
Access-Control-Allow-Origin: http://localhost:8080
Connection: close
Content-Type: application/json
Host: localhost:8000
X-Powered-By: PHP/7.0.12-1+deb.sury.org~xenial+1
{
"test": {
"method": "POST",
"input": {
"word": "new word2"
},
"post": []
},
"words": {
"id": "581f2f118b0414307476f7b3",
"word": "new word2"
}
}
In test
I placed variable obtained in php
by:
$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'),true);
$post = $_POST;
We can see that $_POST
is empty. If I use javascript:
$(form).submit(function(e) {
var url = "http://localhost:8000/words";
var data = {"word" : form.elements["word"].value };
$.ajax({
type: "POST",
url: url,
data: data,
dataType: 'json',
success: function(data)
{
console.log(JSON.stringify(data));
}
});
e.preventDefault();
});
I obtain the following console log:
{
"test":{
"method":"POST",
"input":null,
"post":{
"word":"word from form"
}
},
"words":{
"id":"581f34b28b0414307476f7b6",
"word":null
}
}
Now input
is empty. Word is null because I am processing $input["word"]
, from php://input
. My questions:
- Should I process
$_POST
, or check both variable? - How about best practices of using these methods?
- Can I send
php://input
from browser or$_POST
from command line toll likehttpie
?