Is That My Book : Tidying the API

I’ve been busy progressing with my Is That My Book application, but lately, 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:

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:

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.

Here’s the code on GitHub with the first post here and the next one coming soon!


Written by Stephen Moon
email: stephen at

Hey! Did you enjoy reading this? If you did and would like an email when I add new content, just subscribe to my list. You can unsubscribe at any time.

Leave a Reply

Your email address will not be published. Required fields are marked *