php-mod/curl

json post

Closed this issue · 8 comments

In version 2, you force post data to be array. That prevents you from sanding raw json post requests. I guess that CURLOPT_POSTFIELDS can also take string values.

This release is rethink or Curl Class Library.

To know how to implement Json, I need to know some informations.

To url that you need to get, what it expected as a data? Can I have an example?

maybe a method like:

public function postJson($json)
{
    return $this->post(json_decode($json));
}

could be enough?

In version 2, I try that things will be clear, I don't like mixed arguments in methods.

An explicit API method will do for sure. It's just not possible at all now. An API I'm using is designed to consume raw json, not form data.

curl -H 'Content-Type: application/json' \
    -d '{"name": "Kosice", "type": "city", "country": "Slovakia", "region": "KE", "lon": 21.25, "lat": 48.7166667, "description": "Michaels hometown"}' \
    -X POST http://ewt.local/pois

This example is good, It helped me to understand this case. I think in somthing like this:

public function post(array $data)
{
    // check if we are in json mode, something like this:
    if($this->mode == self::MODE_JSON) {
        $dataToPost = json_encode($data);
        // add necessary headers,
        ...
        // do json post
        ...
    } else {
        // do the post with the $data array
        ...
    }
}

There are way too many problems on these few lines.
The main problem lies in method signature. Please don't force array if you want to support raw data.
Also please don't make assumptions about headers. One might use hal+json or completely custom content type.
Lastly, please don't encode data for users. It may be incredibly hard to serialize data with high complexity.

I see. Now there is two classes and they will be more.

The first class is Curl, this class will do any encoding. (If is the case now, I will change it to do any encoding).

The second class is Client: This class will do some basic encoding for users.

Now I am thinking in a third class: JsonClient.

People who needs specific things should use the Curl class, and people with standard basic could use Client and JsonClient.

nadar commented

@amouhzi i was looking for such a method a certain times, maybe we could just create postJson(array $jsonValues) - would be done quickly. should i send a PR?

Hi @nadar, Yes you can send a PR and it will be merged quickly.