Reputation: 1265
I am working on a PHP REST API. I would like require a user key to access the API. I am not sure how to do this though, do I just issue a key and have them send it in a POST
or with GET
on each API request? Please help me explain in the simplest of terms possible if you can, I know this is something a lot of people want to do and it confuses a lot of people not just myself.
Also I would like to be able to limit usage, I was thinking of storing each hit in a MySQL database or something in Memory even. I just saw this in the header of a Github API request
X-RateLimi-Limit 5000
and X-RateLimi-Remaining 4996
and the number decreases by 1 on each hit, is this some kind of built in limiter?
Upvotes: 1
Views: 680
Reputation: 1126
Just require clients to register with your site, create a record in your CLIENTS table, issue them a unique, non easy to guess id then with each api access require that id to be included in request, either in GET or POST on in the header.
Validate it with every request, return error code if id is not present or invalid.
For rate limiting you are correct, you need to have a separate table for storing count of requests per client and then generate these response headers with X-RateLimit counters.
It's not that hard, really.
I wrote an API that does that for my project, you are welcome to look at the source code, it's in the Api folder, here https://github.com/snytkine/LampCMS/tree/master/lib/Lampcms/Api/
and entry point to API calls is this https://github.com/snytkine/LampCMS/blob/master/www/api/api.php
url for adding new app is: http://support.lampcms.com/index.php?a=editapp
Upvotes: 1