CodeIgniter Forums
How should I implement x-api-key and api rate limit in CodeIgniter 4 ? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: How should I implement x-api-key and api rate limit in CodeIgniter 4 ? (/showthread.php?tid=81937)



How should I implement x-api-key and api rate limit in CodeIgniter 4 ? - kabeza - 05-24-2022

Hi

I have a bunch of ResourceController controllers which build a simple api rest
Then I have a filter with this before code (which is assigned only to api routes)

Code:
Services::response()->setHeader('Access-Control-Allow-Origin',$base_url);
        if (strtolower($request->getMethod()) === 'options') {
            return Services::response()
                ->setHeader("Access-Control-Allow-Headers",
                    [
                        'X-API-KEY',
                        'Origin',
                        'X-Requested-With',
                        'Content-Type',
                        'Accept',
                        'Access-Control-Request-Method',
                        'Authorization',
                    ])
                ->setHeader("Access-Control-Allow-Methods", ['GET', 'POST', 'OPTIONS', 'PUT', 'DELETE']);
        }

I have to implement for all the api controllers, the following

1. X-API-KEY
2. API rate limit (fixed for all routes, very basic)

Which would be the best way to implement each? Create a new filter for each feature?
Does anyone have any useful links to share to get started?

Thanks a lot


RE: How should I implement x-api-key and api rate limit in CodeIgniter 4 ? - iRedds - 05-24-2022

New filter for each feature.
This will make unit testing easier.
And it will reduce the chance of breaking everything by changing some part of the code.


RE: How should I implement x-api-key and api rate limit in CodeIgniter 4 ? - kenjis - 05-25-2022

Rate Limiting sample code:
https://codeigniter4.github.io/CodeIgniter4/libraries/throttler.html#rate-limiting


RE: How should I implement x-api-key and api rate limit in CodeIgniter 4 ? - kabeza - 05-26-2022

Thanks @iRedds @kenjis