Search code examples
phpjsonzend-framework2

Request to Random.org API with ZendFramework2


I'm quite new to ZF2 and I wanted to create some app utilizing external API. I have successfully created method to send requests to random.org API but as a response it sends me an error connected with parsing. I have no idea what I'm doing wrong and how to improve my method to get proper data in response.

Here is my method used to send request (I have intentionally changed api key and in my app I'm using the proper one):

public function makeRequest()
{
    $data = array(
        'jsonrpc' => '2.0',
        'method' => 'generateIntegers',
        'params' => array(
            'apiKey' => '00000000-0000-0000-0000-000000000000',
            'n' => 10,
            'min' => 1,
            'max' => 10,
            'replacement' => true,
            "base" => 10),
        'id' => 23866,
    );

    $client = new Client('https://api.random.org/json-rpc/1/invoke', array(
        'adapter' => 'Zend\Http\Client\Adapter\Curl'
    ));
    $client->setEncType(Client::ENC_FORMDATA);

    $request = new Request();
    $request->setUri('https://api.random.org/json-rpc/1/invoke');
    $request->setMethod('POST');
    $request->getPost()->fromString(json_encode($data));
    $response = $client->send($request);

    return $response;
}

And here is the content of response:

["content":protected]=> string(87) "{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error","data":null},"id":null}

Solution

  • from ZF2 Request Reference, you can find setContent() function, could you try that instead of getPost()->fromString()?

    public function makeRequest()
    {
        $data = array(
            'jsonrpc' => '2.0',
            'method' => 'generateIntegers',
            'params' => array(
                'apiKey' => '00000000-0000-0000-0000-000000000000',
                'n' => 10,
                'min' => 1,
                'max' => 10,
                'replacement' => true,
                "base" => 10),
            'id' => 23866,
        );
    
        $client = new Client('https://api.random.org/json-rpc/1/invoke', array(
            'adapter' => 'Zend\Http\Client\Adapter\Curl'
        ));
        $client->setEncType(Client::ENC_FORMDATA);
    
        $request = new Request();
        $request->setUri('https://api.random.org/json-rpc/1/invoke');
        $request->setMethod('POST');
    
    
        //$request->getPost()->fromString(json_encode($data));
        $request->setContent(json_encode($data));
    
        $response = $client->send($request);
    
        return $response;
    }