Is That My Book : Tidying the API
I’ve been busy progressing with my Is That My Book application, but lately, I’ve mainly been focusing on fixing up the API to attempt to make it sparkle. As I have said before, this is step one with making a front-end to it, the next part. API Interface Changes So what’s changed? Well, I got rid of the genres part. Not needed. Not wanted! I also added in a DELETE method which Slim makes quite straight forward as you can see below:
1 | $app->delete('/books/{id}', function($request) { |
Internal Changes Within the API, I have cleaned up the input to make sure no stray spaces make their way into the database. I have also standardised on prepared statements; there were a couple of places where I was just taking an ID field from the request, and that was a little risky. It only required a couple of modifications, so was well worth it. On that note, take a look at The Hitchhiker’s Guide to SQL Injection Prevention which is a really useful resource. A small change to how the routes are organised is something I have seen in other frameworks. Basically, since all of the routes began with /api/, I didn’t need to keep writing that. By grouping them, I could write that part once and have it applied to all the routes within it. This is best illustrated by the actual code:
1 | $app->group('/api', function() use ($app) { |
Note how the GET doesn’t need the /api
any longer. Another nice touch was adding in some middleware to allow for the use (or non use) of trailing slashes on the end of routes. Without it, if I went to /api/books
, it would work, but should I have added a trailing slash, it wouldn’t: /api/books/
. For this, I used oscarotero’s middleware. Installing it is a breeze - take a look at the official docs and this.
Other last changes I made were to better handle errors with the database by again, drawing on PHPDelusion’s pages, but also re-organising the structure of my application based on an excellent set of slides from Rob Allen’s community talk.
That’s all for now, but you can go back to the first article in this series here should you have arrived part way through.
Hi! Did you find this useful or interesting? I have an email list coming soon, but in the meantime, if you ready anything you fancy chatting about, I would love to hear from you. You can contact me here or at stephen ‘at’ logicalmoon.com