Slim4: API usage tracking


I have build a API engine powered by Slim4, and I’d like to some API usage statistic and store it to database. Is there any good way to implement it without adding logging functionality to each and every API endpoint code?

Hello @artello!

Looks like a application-middleware will suit your needs. This way, you can write some code to grab what you need from request and store it wherever you like.

Note that you can “bind” a middleware to all routes, a group or a specific route, so it’s simple to set up accordingly.

1 Like

Hello @raffster!

Thanks a lot for an advise! I did a very basic middleware which captures some interesting parameters Iike API endpoint & and query params and stores it in database. The very strange thing is that I can’t get request payload while processing request in the Middleware by issuing a $request->getParsedBody() if ContentType is ‘application/json’. At the same time I have no issues to get query parameters once Middleware processing is finished and query reaching main code. At the same time
if ContentType set to ‘application/x-www-form-urlencoded’ the params get correctly decoded…

Any ideas?

Its nice to see it helped somehow.

Ohh, Unfortunately, I don’t see how its depends on content-type.

The request body is parsed by a middleware, actually. So, it is conditioned by the middleware order.

In Slim, the last middleware you add are the first to be executed. This means that if you want to have the BodyParsingMiddleware to run before some specific middleware that requires the parsed body you have to add that specific middleware first and then register the BodyParsingMiddleware.

Could you check and test that?
I’ll see if I find something that could be related to content-type…

Indeed, you spotted my issue correctly, I messed up with the middleware order and tried to access getParsedBody before BodyParsingMiddleware did its job. Thanks for pointing this out!

Great! Nice to know you have it done!


1 Like

I am using such approach in my CMS

I am saving statistics of tokens usage for my APIs