Reputation: 148
I'm trying to run a flask API in a specific port number as below,
from flask import Flask, request
from pymongo import MongoClient
import json
app = Flask(__name__)
@app.route("/")
def hello():
return "Befriend Registration"
@app.route("/reg", methods=["POST"])
def pushDB():
somedata= request.get_json()
return json.dumps({"status":"OK", "Data": somedata})
if __name__ == '__main__':
app.run(port= 34000, debug=True)
And trying to send data using PHP
<?php
$url = 'http://127.0.0.1:34000/reg';
$data = array("collection" => "RapidAPI");
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($curl);
echo $response;
curl_close($curl);
?>
But every time API is receiving null
The response body is something like
{
status: "OK",
Data: null
}
Upvotes: 0
Views: 778
Reputation: 324
Flask needs to know that it is receiving "json". In your PHP script you need to add additional "Content-Type" header.
<?php
$url = 'http://127.0.0.1:34000/reg';
$data = array("collection" => "RapidAPI");
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
$response = curl_exec($curl);
echo $response;
curl_close($curl);
Upvotes: 1