Building APIs into your software, especially when they’re exposed as a web service, is a fantastic way to broaden engagement with your open source software project. APIs allow people to extend and integrate with your software without having to touch your core codebase, which is good for maintainability and for uptake.
Moodle is a fantastic example of this. As well as providing a wealth of internal APIs for writing plug-ins, it exposes functionality via web services which has allowed the community to develop mobile apps which use Moodle’s data and features without requiring special hooks in the core code.
When designing an API, it’s important that you do so in a way that people will be able to use it easily. PHP aficionado Lorna Jane Mitchell‘s been gathering examples of how not to do it, and has identified 3 deadly sins of API design, to steer you in the right direction:
- Using incorrect error codes.
Many APIs exposed through web services use a convention called Representational State Transfer, or REST. The idea of REST is to use HTTP as your API’s protocol, keeping your overheads to a minimum. HTTP already has a well defined vocabulary of methods and return codes, so doesn’t need extra data being sent back and forth to provide this information. If you’re going to write an API that uses REST, don’t return a 200 code (OK) and then send back an error message in the response’s body. There’s an error code to cover pretty much any eventuality, so make use of them. This allows developers to write code that identifies the type of error and handles it appropriately.
- Being Inconsistent.
Developers want an easy life. When they call your API, they want to be able to predict what will happen. Follow consistent conventions in your vocabulary (especially regarding singular and plural nouns), and don’t change the type of data returned depending on the result of the query.
- Documenting Poorly.
This applies throughout your project, but especially for external APIs as these will be the first point of call for someone looking at integrating or extending your software. Expecting people to read through your code to work out how to use your API isn’t going to win you any friends or contributors. Worse than this is letting your documentation be incomplete, incorrect or out of date, leaving people to find the mistakes and work around them by trial-and-error.