Malabika Sen
Malabika Sen

Reputation: 1

How do I send JSON request AND post form data request together?

So this is an API which should accept the following parameters in POST request:

token (as form data)
apiKey (as form data)
{
"notification": {
    "id": 1,
    "heading": "some heading",
    "subheading": "some subheading",
    "image": "some image"
     }
 } (JSON Post data)

Now my problem is that i'm not able to send the form data and JSON data together in the same POST request. Since, the form-data uses Content-Type: application/x-www-form-urlencoded and JSON needs to have Content-Type: application/json I'm not sure how do I send both of them together. I'm using Postman.

EDIT:

So the api will call the function create and I need to do something like this:

public function create() {


    $token = $this -> input -> post('token');
    $apiKey = $this -> input -> post('apiKey');
    $notificationData = $this -> input -> post('notification');

    $inputJson = json_decode($notificationData, true);
    }

But instead I'm not able to get the JSON data and form data together.

I have to do this to get JSON data only

public function create(){
$notificationData =  file_get_contents('php://input');
$inputJson = json_decode($input, true);  
} // can't input `token` and `apiKey` because `Content-Type: application/json`

Upvotes: 0

Views: 3399

Answers (1)

deceze
deceze

Reputation: 522125

Several possibilities:

  1. Send the token and key as query parameters and the JSON as request body:

    POST /my/api?token=val1&apiKey=val2 HTTP/1.1
    Content-Type: application/json
    
    {"notification": ...}
    

    In PHP you get the key and token via $_GET and the body via json_decode(file_get_contents('php://input')).

  2. Send the token and key in the Authorization HTTP header (or any other custom header):

    POST /my/api HTTP/1.1
    Authorization: MyApp TokenVal:KeyVal
    Content-Type: application/json
    
    {"notification": ...}
    

    You get the header via, for example, $_SERVER['HTTP_AUTHORIZATION'] and parse it yourself.

  3. Make the token and key part of the request body (not very preferred):

    POST /my/api HTTP/1.1
    Content-Type: application/json
    
    {"key": val1, "token": val2, "notification": ...}
    

Upvotes: 3

Related Questions