PatrickL's avatar

JSON API format and Laravel

I am making an API in Laravel that is compliant with the JSON API standard, which can be fund here: http://jsonapi.org/format/

I have two questions though. Both of them have to do with the Server responsibilities section of the spec.

The first question has to do with the following requirement:

"Servers MUST respond with a 415 Unsupported Media Type status code if a request specifies the header Content-Type: application/vnd.api+json with any media type parameters."

My question is how do I check request headers for media types and if they have parameters. (This check will be done using middleware).

My second question is regarding whether or not there is a way to modify responses automatically to include the required metadata in JSON API? Like, instead of adding the necessary media type (Content-Type: application/vnd.api+json) in each and every response, can I just define it in one place and have it automatically added in all my application's API responses? This is not really a requirement. It would just make things easier to modify or update in the future.

Thanks.

0 likes
3 replies
bobbybouwmann's avatar

Well the first one can be pretty easily checked for by fetching all the headers from the request and checking on it

// Inside your middleware
$headers = request()->headers->all();

if (isset($headers['content-type']) && $headers['content-type'] === 'vnd.api+json') {
    return response()->json(['message' => 'Unsupported Media Type'], 415);
}

Note: You can make this code more readable using collections and stuff, but I think you get the idea this way ;)

For your second question you need some kind of abstraction right. So you can for example create your own response class that always has some kind of headers. I would personally build a class around the response->json() helper and just pass in your own extra details you need ;)

You might find this series interesting for that: https://laracasts.com/series/incremental-api-development

Let me know if that is clear for you!

PatrickL's avatar

@bobbybouwmann Thanks. This helps a lot.

Would I also be able to check for media type parameters using this same fashion?

Thanks for the help.

Please or to participate in this conversation.