dtwbp26022 2016-03-23 13:23
浏览 34

如何调用MongoLabs(mongoDB)RESTFUL APIS在php中添加文档?

On the MongoLabs documentation to insert a document the following jQuery code is given in the example: http://docs.mlab.com/data-api/

    $.ajax( { url: "https://api.mlab.com/api/1/databases/my-db/collections/my-coll?apiKey=myAPIKey",
      data: JSON.stringify( { "x" : 1 } ),
      type: "POST",
      contentType: "application/json" } );

I have to call the RESTFULL API end point via PHP for my android app..

How do i make a POST request in php to call the MongoLABs data APIS?

How to convert the above jquery code to php code?

I have tried the following code but no luck. Can someone tell the mistake in the following code or tell how to do it using php?

   <?php
   $x=array(
    'x' => 2
);
   $data=json_encode($x);
   echo $data;
   $postdata = $data;


    $opts = array('http' =>
        array(
            'method'  => 'POST',
            'header'  => 'Content-type: application/x-www-form-urlencoded',
            'content' => $postdata
        )
    );

    $context  = stream_context_create($opts);

    $result = file_get_contents('http://api.mlab.com/api/1/databases/mydb/collections/mycoll?apiKey=xxxxxxxxxxxxxxxxxxxxx', false, $context);

    echo $result;
    ?>
  • 写回答

1条回答 默认 最新

  • dongyan4157 2016-03-24 04:32
    关注

    Got the mistake: If anyone has the same issue or want to use the mLabs data api.. Use the following:

        $x=array(
            'x' => '2'
        );
        $data=json_encode($x);
        //echo $data;
    
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/json',
                'content' => $data
            )
        );
    
        $context  = stream_context_create($opts);
    
        $result = file_get_contents('https://api.mlab.com/api/1/databases/mydb/collections/mycoll?apiKey=xxxxxxxxxxx', false, $context);
    
        echo $result;
    

    But try to avoid using the DATA apis as the key is vulnerable and anyone with the key will have access to your entire DB..

    评论

报告相同问题?