Error handler should return JSON

I’m building an API with Slim 3. How do I setup that errors should be returned as JSON? For example, 405 method not allowed is returning a HTML page by default.

Slim’s error handlers will return the JSON if the client’s Accept header is correct.

i.e.

curl -H "Accept: application/json" http://myslimapp.example.com/not-an-end-point

will produce a response of:

{"message":"Not found"}
1 Like

Cool, that worked, thanks!
Is it possible to set the default content type to json? I will only support json in the API.

Hi akrabat,
I am using slim to write a api and run into this thing today. My app has api routes and html routes and i wrote a middleware to apply to the api routes that changes the content-type to application/json.
If i have previously (before a exception is thrown) changed content type to “application/json” shouldn´t respond as json also?

Thanks.