OT - need help with PHP

Chris Angelico rosuav at gmail.com
Fri Feb 1 15:16:07 EST 2019


On Sat, Feb 2, 2019 at 7:08 AM bob gailer <bgailer at gmail.com> wrote:
> HOW TO CALL A FUNCTION USING VOIP.MS REST/JSON API
> The following samples show how to get all Servers Information from our
> database and how to select a specific Server for your display purposes.
>
> Please Note:
> - When using our REST/JSON API you need to send the Method to be used
> and the Required Parameters as part of the URL.
> - By default the output Content-Type is "text/html".
> - If you want the output Content-Type to be "application/json", add the
> following to your URL: &content_type=json

Cool, this is the most important information.

> PHP - Using cURL POST - Sample Code
>
> |$postfields = array( 'api_username'=>'john at domain.com',
> 'api_password'=>'password', 'method'=>'getServersInfo',
> 'server_pop'=>'1'); $ch = curl_init(); curl_setopt($ch,
> CURLOPT_RETURNTRANSFER, true ); curl_setopt($ch, CURLOPT_POST, true );
> curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); curl_setopt($ch,
> CURLOPT_URL, "https://voip.ms/api/v1/rest.php"); $result =
> curl_exec($ch); curl_close($ch); $data=json_decode($result,true);
> print_r($data); |

The PHP array can be converted easily into a Python dictionary:

postfields = {
    "api_username": "john at domain.com",
    "api_password": "password",
    "method": "getServersInfo",
    "server_pop": "1",
}

I don't know what the CURLOPT_RETURNTRANSFER option does, so I'm going
to ignore it.

Since there's nothing obvious about the format of POST data, I'm going
to assume that it's meant to be form encoded. Give this a try and see
if it works.

r = requests.post("https://voip.ms/api/v1/rest.php", data=postfields)

Many APIs use JSON rather than form encoding, in which case you'd say
"json=" instead of "data=", but that seems unlikely in this case.

> Note: I have edited these examples by removing unnecessary stuff, to
> make their size reasonable.

Assuming you haven't omitted anything important, the translation to
requests should be fairly straight-forward.

> One of my needs is to upload a .wav file. The vendor requires the file
> to be encoded into base64  and the result string included in the POST
> data, which can lead to enormously long POST data. I can successfully
> use GET to send very short .wav files, but the url length limit is
> quickly reached for a reasonable length recording. Trying to use the
> POST ability that allows me to specify the file by path fails at the
> vendor side.

http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file

You'd need to match the PHP examples to the way Requests does file
uploads, but it ought to work.

ChrisA



More information about the Python-list mailing list