0

Im new to PHP trying to figure out how to post an API-Call with data to one of my Endpoints written in Python.

My Endpoint expects a payload which I load into a dictionary with the request module. After that I just access the payload dictionary and process the data. I just don't know how to correctly post the data in PHP so I can use request.json to parse it in a dictionary.

The Question here hasn't been answered and is not as that well explained: how to send Request Payload with php cURL?

This Question has been answered but I don't know how that translates into PHP cURL: How do I POST JSON data with cURL?

My Python endpoint:

@application.route('/generate', methods=['POST'])
def generate():
    messageBody = {}
    headers = request.headers
    payload = request.json

    try:
        auth = headers.get("X-Api-Key")
        if token(auth):
            credentials = credentialsFunc(auth)

            try:
                processed= gen(payload['type'], payload['quantity'], payload['location'])

How do I post the relevant data to a Python endpoint? My curl in PHP so far:

$data = json_encode(array(
                "location" => $country,
                "type" => $type,
                "quantity" => $quantity
            ));

$ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, getenv('REDIRECT_GENERATION_URL'));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);

            $headers = array();
            $headers[] = 'X-Api-Key: ' . $key;
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);     <--My endpoint can't parse the data
            echo $data;

            $result = curl_exec($ch);
            if (curl_errno($ch)) {
                echo 'Error:' . curl_error($ch);
            }

            $res = json_decode( $result, true );
            echo $res['balance']
            curl_close($ch);

How do I send a PHP POST-Request so my Python endpoint can parse it with request.json?

1 Answers1

0

Using json_encode inside PHP was actually the correct way to prepare a JSON to use with CURLOPT_POSTFIELDS. Turns out my Endpoint had some version problem with a Python module I was using.

If Google brings you here and you wonder how you can send a payload with PHP, then this is the way:

$data = json_encode(array(
          "location" => $country,
          "type" => $type,
          "quantity" => $quantity
        ));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, getenv('REDIRECT_GENERATION_URL'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = 'X-Api-Key: ' . $key;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    

$result = curl_exec($ch);
if (curl_errno($ch)) {
   echo 'Error:' . curl_error($ch);
   }

$res = json_decode( $result, true );
print_r($res);
curl_close($ch);