API Caching

I’ve created an API and I want to enable caching. The API is written in PHP, is RESTful and delivers the results in XML. I’ve googled PHP and caching API and have only come across ways to get past social site APIs, not how to cache your own. The API is accessed via desktop client and browser. I’m using the DOMDocument class and returning text, plus image URLs, all of which could benefit from caching.

Any suggestions on where to start? Developers access the API with tokens, so I’d like to enable hourly limiting, etc.


An ideea is to store the data of the returned XML into a database (mysql table) into a column associated to the tocken and time.
Then, before processing data, check the token and time. If correspond, gets xml stored in database, else, processes data and saves xml for cache in database.

That won’t really work because each time the API is requested the returned data is different, so storing the XML would be pointless. I have thought about storing the token or user IP in mysql and then checking against that, but that just adds a ton more connections to an already very active API, and I’m trying to limit the amount of queries.

I suppose I could store the token and access time in a flat file and check against that, which would go towards limiting, though I’m still trying to figure out a caching mechanism. Perhaps there isn’t one for an API?..

Thanks for the suggestion :slight_smile:

Perhaps i’m confused.

“I want to enable caching” “each time the API is requested the returned data is different”… these… appear to be opposing statements?

Exactly. :slight_smile:

I’ve figured this out, using a similar method to what MarPlo suggested. It won’t be caching, per se. Instead I’m just going to write everything to text files and, when a request comes in and a text file isn’t on the server then do the db query, write the results to the text file and then return the text file.

While each API request will be different, they will all access existing records, so by writing those records to a text file (with the record’s ID number as the file name) when the record is created or updated, I’ll only have to do a db query for the record ID number and return the file.

I’d be interested in performance gains you achieved by this. To me this sounds like you are building a small file-based database in PHP to offload the main database, which essentially is also file-based - and by designed tuned for performance as well… I’d personally enable mysql query cache for this purpose and leave all the queries as they are and much less complicated code. Was your system running slow that you went to such great lengths as to roll your own file-based caching?