A handful of pointers for making good RESTful services, or at least avoiding the worst of the pitfalls. Code examples in PHP, this talk was originally given at OSCON 2012
It has a single endpoint • All requests are POSTs • Response metadata is in the body, not header • There are verbs in the URL • The URL includes method names
function render($content) { header('Content-Type: application/json; charset=utf8'); echo $this->buildOutput($content); return true; } /** * Function to build output, can be used by JSON and JSONP */ protected function buildOutput ($content) { $content = $this->addCount($content); $retval = json_encode($content, JSON_NUMERIC_CHECK); return $retval; } }
either resources or collections of resources We use HTTP verbs to operate on these resources Verb Collection Resource GET fetch resources fetch resource POST create a resource in this collection PUT create or update a resource here PATCH update part of a resource DELETE delete a resource
GET http://example.com/articles/42, change the "active" flag, and PUT it back Make a subresource, then you can just work with http://example.com/articles/42/active
to agree what formats to use. Common examples: • application/json • application/xml • text/html Next stage: use Media Types for custom/versioned representations
correct format before we bail global $request; header("Status: " . $e->getCode(), false, $e->getCode()); $request->view->render(array($e->getMessage())); } set_exception_handler('handle_exception');
than debug output if the client expects JSON • Proxy or network analyser • Inspects traffic without application changes • e.g. Wireshark or Charles proxy • Drop back to last known good outcome • Increase complexity in "baby steps"
own code - have a class that wraps it. You can: • cache results if it is slow/flaky • replace it in one place later, if needed • write tests to check the API is still doing what you expect • write a mock object to replace it with for your own tests