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

togo_hgl's avatar

Tracking API Requests including their Size

Hi there,

I want to track API Requests but not just the URL but also the size of the answer in eg bytes

Therefore, my first idea was to just spam into a db table all the requests like

Request | Size | Time

get_user | 1024 | ...

So, probably I need to like stringent every answer right? Is there any good way of doing that and also, where can I have this code to not put this into every API controller? Middleware?

Thanks in advance!
0 likes
6 replies
automica's avatar
automica
Best Answer
Level 54

@togo_hgl create a middleware and add it to your api routes.

and add something like:

    /**
     * @param Request $request
     */
    private function logRequest(Request $request): void
    {
        UserRequest::create([
            'user_id' => ($this->getToken($request))->tokenable_id,
            'host' => $request->server('HTTP_HOST'),
            'route' => $request->server('REQUEST_URI'),
            'method' => $request->server('REQUEST_METHOD'),
            'user_agent' => $request->header('user-agent'),
            'duration' => $request->server('REQUEST_TIME')
        ]);
    }
2 likes
togo_hgl's avatar

but is there any way to calculate the size of the response which got sent?

automica's avatar

you can use $request->server('CONTENT_LENGTH')

2 likes
togo_hgl's avatar

Thank you for that awesome help! ❤️

1 like
togo_hgl's avatar

Using "REQUEST_TIME" shows only the timestamp when the request started ... is there any way to calculate the full time of the request from start to finish or .. sadly the "CONTENT_LENGTH" is not giving me any results when using GET requests.

1 like

Please or to participate in this conversation.