2017-10-29 9 views
0

PHPで書かれたRESTful APIを使用するための小さなPythonユーティリティを作成しています。これまでのところ、すべてGETリクエストで正常に動作しますが、POSTリクエストを実行しようとすると、レスポンスがステータスコード200を返しても、新しいレコードはデータベースに作成されません。POSTリクエストでデータベースに新しいレコードを作成できませんでした

from httplib2 import Http 
import json 

root_dir = 'http://restphp/restphp/public/api/' 
not_finished = True 

http_obj = Http() 

def get(url): 
    resp, content = http_obj.request(url) 
    return resp, content 

def post(url, data): 
    resp, content = http_obj.request(
     uri  = url, 
     method = 'POST', 
     headers = {'Content-Type': 'application/json; charset=UTF-8'}, 
     body = json.dumps(data) 
    ) 
    return resp, content 

# Code for getting data from input stream 
# ... 

data = { 
    'first_name': first_name, 
    'last_name': last_name, 
    'email': address 
} 

resp, content = post(root_dir + 'customer/add', data) 
print(resp) 

これが出力されます。

{'date': 'Sun, 29 Oct 2017 19:27:29 GMT', 'server': 'Apache/2.4.23 (Unix) OpenSSL/1.0.2j PHP/7.0.13 mod_perl/2.0.8-dev Perl/v5.16.3', 'x-powered-by': 'PHP/7.0.13', 'content-length': '109', 'content-type': 'text/html; charset=UTF-8', 'status': '200'} 

これは、(私がSlimフレームワークを使用しています)新しい顧客を作成するためのルートです。 ChromeのRestEasy extensionでAPIを確認しましたが、すべて正常に機能します。

# Add new customer 
$app->post('/api/customer/add', function(Request $request, Response $response) { 
    $first_name = $request->getParam('first_name'); 
    $last_name = $request->getParam('last_name'); 
    $phone  = $request->getParam('phone'); 
    $email  = $request->getParam('email'); 
    $address = $request->getParam('address'); 
    $city  = $request->getParam('city'); 
    $state  = $request->getParam('state'); 

    $sql = "INSERT INTO customers (first_name, last_name, phone, email, address, city, state) VALUES 
    (:first_name, :last_name, :phone, :email, :address, :city, :state)"; 

    try { 
     $db = new DB(); 
     $db = $db->connect(); 

     $stmt = $db->prepare($sql); 
     $stmt->bindParam(":first_name", $first_name); 
     $stmt->bindParam(":last_name", $last_name); 
     $stmt->bindParam(":phone", $phone); 
     $stmt->bindParam(":email", $email); 
     $stmt->bindParam(":address", $address); 
     $stmt->bindParam(":city", $city); 
     $stmt->bindParam(":state", $state); 

     $stmt->execute(); 

     echo '{"notice": {"text": "Customer added."}}'; 
    } catch (PDOException $e) { 
     echo '{"error": {"text": ' . $e->getMessage() . '}}'; 
    } 
}); 

私は'first_name' column can't be null(全体のデータが送信されていても)、またはBrokenPipeError: [Errno 32] Broken pipeのように、すべての実行にランダムエラーを取得します。

答えて

0

POSTデータで本体にデータが送信されたとき。これを試してください

$value = json_decode($request->getBody()); 
$first_name = $value->first_name 
$last_name = $value->last_name 
$phone  = $value->phone 
$email  = $value->email 
$address = $value->address 
$city  = $value->city 
$state  = $value->state 
+0

私が '$ value'で' var_dump'を実行すると、 'NULL'を取得します。 – Nikola

関連する問題