neomerx / json-api

Framework agnostic JSON API (jsonapi.org) implementation

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Problem with Content-Type: application/vnd.api+json

nebur81 opened this issue · comments

I'm newbie with jsonapi and I made a test to encode an author (using some of your test files) and when I tested it with Postman I get: Content-Type →text/html; charset=UTF-8
Content type should not be application/vnd.api+json?.

I encoded it with: echo $encoder->encodeData($author);

Also I made a test to response only meta information and I get a Content-Type text/html too. I used this code: $encoder->encodeMeta(array(http_response_code(204)));

I'm using v1.x because it's a project with php 5.6. I don't know if I'm making something wrong or there's some other issue.

Attached two images with the response I got in Postman:
img1
img2

Hi, what you're trying to do is usually done something like

$json = $encoder->encodeData($author);

// now reply with a response
$response = new Zend\Diactoros\Response\JsonResponse($json);

// now return the response back to client
...

As you can see the response part is quite simple but very framework dependent. The example above uses diactoros, however there are other very respectable frameworks (e.g. guzzle). Of course, you can use old good header function to send Content-Type as well.

This JSON API framework is framework agnostic so you can use anything you like.

Ok, I will take a look to those frameworks. Thank you so much for help.

Just a clarification, I used this code to get a response according to jsonapi:

$data = $encoder->encodeData($author);
$response = new TextResponse($data, 200, [ 'Content-Type' => ['application/vnd.api+json']], JSON_PRETTY_PRINT);

$emitter = new Zend\Diactoros\Response\SapiEmitter();
$emitter->emit($response);

The response is:

{
    "data": {
        "type": "people",
        "id": "123",
        "attributes": {
            "first_name": "John",
            "last_name": "Dow"
        },
        "links": {
            "self": "http://example.com/api/v1/people/123"
        }
    }
}

Because if I use the class Zend\Diactoros\Response\JsonResponse the response is:
{\n \"data\": {\n \"type\": \"people\",\n \"id\": \"123\",\n \"attributes\": {\n \"first_name\": \"John\",\n \"last_name\": \"Dow\"\n },\n \"links\": {\n \"self\": \"http:\\/\\/example.com\\/api\\/v1\\/people\\/123\"\n }\n }\n}

Absolutely! The JsonResponse internally uses json_encode which is not what you need. I myself use this class.