Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rguttersohn's avatar

How to set content-type from API routes

I am storing data as json in Redis. When I get a cache hit, I am retrieving this json-formatted data from Redis and then decoding it before returning.

That seems like a silly step since it just get re-encoded before sending the response. So I simply returned the json straight from Redis. It saves a good 20 to 30 ms. However it is sending the data as text/html and not application/json.

When I tried setting the content type as so:

return response($cached_data)
                ->header('Content-Type', 'application/json');

... it simply sends the header as a part of the text/html and not a header.

Any idea how to properly set the content type from the api route file?

0 likes
6 replies
gych's avatar

Can't you just use this? It will auto set the content type to application/json

return response()->json($cached_data);
rguttersohn's avatar

That sets the content type to application/json but wraps the data in quotes and essentially makes the client code think it's just a string.

gych's avatar

@rguttersohn You can decode/parse the JSON on the client side to convert it back to its original format.

rguttersohn's avatar

@gych Totally but that is an unnecessary decoding/encoding step. I fully recognize that 20 to 30ms is nothing in the grand scheme of things, but it would be nice to just already-encoded json as is. But I am thinking this may only be possible from routes/web.php.

martinbean's avatar

I fully recognize that 20 to 30ms is nothing in the grand scheme of things

@rguttersohn So why are you spending so much time and effort into “solving” this? Surely there are bigger problems in your app?

rguttersohn's avatar

@martinbean Not a helpful response. I never said I was spending 'so much time' on this. I am hoping to remove a redundant step from my response that was unnecessarily adding time.

Please or to participate in this conversation.