Tips on Writing an API for a Smartphone App

Yesterday, I saw this tweet:

@lornajane @nabeels tips on starting to write an API to interact with Smartphone App?? :-s

I have lots of advice for Olly (whom I know personally) but there's no way it will fit into a tweet! So here it is, in rather longer form :)

Be Consistent

Whatever data format you pick, whatever app you are building, whichever approach you choose, be consistent. Your whole API should call things by the same name, use the same validation rules for everything, and accept parameters in the same order. Every time. Look out in particular for things like singular/plural names, mixing case and parameters which are sometimes optional.

Fail Really Really Excellently

Things will go wrong. This is the way the world works in general, and on the web in particular. Requests sometimes don't arrive, or the responses don't. Disks fill up, databases fall offline, all kinds of weird stuff does happen. All that matters is how you deal with it.

Make all your errors arrive in the same format as the successful response would have. This means that the client can parse it and understand what is there. If you feed HTML into something that wasn't expecting it, something unexpected will happen (actually PHP's json_decode() will cause PHP to segfault if you try hard enough).

Give meaningful error messages. This allows users to help themselves, continue to use your API, hopefully learn to love it - and all without having to bother you in the process. This is the holy grail of API creation!

Keep It Tidy

A Small API is easy to maintain and support, so try to keep your APIs as minimal as possible. Only write functionality that is really needed. Make things flexible so that clients can ask for more or fewer records than the default (especially if the data sets can get large!), and get the result set sorted sensibly - it's very expensive to do those kinds of operations on any kind of large data set on a small device.

Keeping this small is also keeping things simple, and the KISS principle is good advice for all areas of software design.

The Actual Advice

For a non-novice programmer, an API is a project that is absolutely approachable. For sending data to a smart phone, I'd recommend the following:

  • JSON format - it's lightweight, easy to parse, and also relatively easy to debug if you need to
  • RPC style - REST is much cooler, but it's hard to get started with if you haven't used it before, and bad REST just gets everyone upset. You already know how to declare and call a function - so make your API along those lines. Look at wikipedia's JSON-RPC page for some ideas
  • Make sure you understand HTTP headers and status codes, and use them! Use Accept and Content-Type for sorting out data formats, status codes to say if things went well or not.
  • I feel like there should be more advice here ... please add a comment if you know what else I should be telling Olly!

Tools to Help You

You'll be doing a lot of debugging, print_r($_SERVER) is a good place to start with understanding what requests came in. Use wireshark to make sure that you are sending and receiving what you think you are send and receiving. If you need to debug output but doing so breaks your client because it sends nonsense in the data format, use error_log instead.

Most of all, know this: if you can already build a website, you can build an API. Good luck :)

8 thoughts on “Tips on Writing an API for a Smartphone App

  1. Considering the formats you emit: If you want to make the life of your consumers as easy as possible, consider also emitting your data in .plist format - if you are creating the API for consumption by mobile devices, likely some iphones will be among them and iOS has really specialized (=fast) APIs for dealing with plists.

    You can use the Accept-header for clients to tell the server what output they prefer (JSON or plist).

    Then, just deal with your data internally and serialize either as JSON or as plist (https://github.com/rodneyrehm/CFPropertyList) as the very last step

  2. This is great general API design advice, but the 'for a smartphone app' specific items aren't really covered in much detail.

    For a smartphone app, you'll want to take into account the following things in your API design:

    1. It's better to have fewer connections with larger datasets than more connections with small datasets.

    The reason is that on mobile networks compared to wifi networks the routing overhead of individual requests is much, much, much larger. Setting up the connection is a significant portion of the api call, so it's better to combine. Pure rest apis with many small resource calls are typically sluggish in a mobile app that runs over a 3G network. I practice 'scenario driven design' here, in other words don't work from the resources upwards, but from the needs of the application down.

    2. Use http compression. Any data you can save between phone and api is a gain in performance.

    3. Avoid verbose protocols such as SOAP or XML in general, mostly for the same reason as 2.

    4. Use caching headers and implement them properly in your app; an app that doesn't make a call because it has retained data is a huge performance gain in a mobile app; however you do want control on the server to make sure data isn't retained for too long. This is where caching headers help you.

  3. @lornajane

    Does json_decode() still seg-fault with bad JSON? That's really really poor. It needs fixing.

    @Ivo

    "It's better to have fewer connections with larger datasets" - Modern smart phones have loads of memory compared to phones of old but there must be a point at which a really large dataset is actually problematic in itself.

    Developers should just be aware of all the resource limitations that you get on embedded development. Restricted memory, processor, bandwith,; slower connection times; and so on.

    Finally test on the most rubbish platform that will be using your service. Not the best!

  4. @Cyberspice: There's always a tradeof between one or the other; however a larger dataset does NOT mean that you need to load all of it in memory; if you have really large datasets you can process them progressively.

    But if you have a choice between 20 calls of 1K each or 1 call of 20K, go for the latter.

  5. I used cURL for testing and simulation of a smartphone calls, and for mixed browser/native app applications I would recommend modify Headers plugin for firefox if you needed to modify HTTP headers

  6. Pingback: Linkpool Nummer 30 | PHP Gangsta - Der PHP Blog mit Praxisbezug

  7. Just found this post again, and re-read. Comments are great and initial advice will really help with an upcoming project! Bookmarked! ;)

    Thanks to all

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>