Adding a Simple API
Today I wanted to do something fairly simple - add a JSON API to Ugako image search. This is important as part of the plan to ultimately have a Wordpress plugin (and maybe more).
In the majority of occassions we strive to write code that separates tasks out into functions the first time round. This helps make it more manageable and maintainable and makes it more readable and modifiable if others work on the code. In short, it saves time.
There's an exception to this that I sometimes make though. Where I'm not sure if a piece of code will work and where that code is linear (task follows task follows task) and where any potential repetition is slight, it's quicker to just write test code first to see if it works. In the case the code doesn't work, no additional time has been spent on it and where it needs tweaks it's easy to see what needs changing in code you just wrote.
That's just a temporary solution though and that's a bit how the search function was. The function does every task to display the results from querying to the actual output. Now I was adding in a JSON output, it was time to do some tidying up. Obviously if I was a bad programmer, I could copy the whole search function to a new JSON one and simply change the HTML format to JSON, but I try to be good. The problem with duplication like that is if I later change the way I choose to rank images (which is quite likely to happen) then I have to remember to change two sets of almost identical code.
So the first task was to break the existing search function out into multiple functions.
The difficult part is working out what those functions should be and what they should return. After that it'same easy. I ended up with code that converts a vector into a list of search results. The regular search function then ends up processing this list and outputing HTML. For the JSON it's even easier, we simply take the list of results and use a python library to convert it to JSON. By giving that a separate route (url), then we have a JSON interface that other code can query.
You can see what the JSON output looks like for a query by following this example link.
As this was a small change, I wanted to try something a little bit different to just this write-up to given an insight into the process. So I recorded this video. It's live (I've editted, but to remove rambling and make it shorter). I've tried to explain what I'm thinking at each point and why. I hope that shows the process and that it's not always perfect and things sometimes don't work. That programming, of even fairly simply things, is an art where a programmer is making decisions that influence the rest of the work and sometimes just trying things.