-
Notifications
You must be signed in to change notification settings - Fork 301
Guide: REST
TouchDB's intrinsic API, like CouchDB's, is based on HTTP and follows the architectural style known as REST (Representational State Transfer), in which resources identified by URLs act as "objects" and the basic HTTP verbs act as "methods". This maps very well to the fundamental create / read / update / delete (CRUD) operations of a database. It's also similar to the read-write extension of HTTP, WebDAV.
I won't go into the exact details of the API, because it's not normally used by mobile or desktop applications: instead they use a more convenient native CouchDB wrapper API such as CouchCocoa on iOS/Mac OS, or Ektorp on Android. However, the principles of it are useful to know.
One interesting difference is at the very top level of the URLs: the scheme itself. CouchDB of course uses the http: or https: schemes. TouchDB doesn't communicate with your app over HTTP sockets because it's already built into the app; instead it fakes it by registering a custom touchdb: scheme. As long as your app uses the platform-standard URL access API (NSURLConnection on iOS or Mac OS), it can make HTTP request using this scheme instead of http: and they'll be routed directly to the TouchDB thread.
-
Everything has a URL. Databases, documents and attachments all have their own URLs. And the URLs form a hierarchy, using the IDs as components of the path. So for example, the URL
touchdb:///mydb/doc1/readme.txtrefers to the attachmentreadme.txtof the documentdoc1in the databasemydb. (Revisions have URLs too, but they're not quite as clean: to name a specific revision of a document, a?rev=query parameter is added.) - PUT and POST create documents. A PUT to the URL of a nonexistent document creates it. A POST to a database URL creates a new document with a randomly-generated UUID for its ID.
-
GET reads a document. A GET of a document's URL returns the current revision in JSON form, including its current revision ID in the
_revproperty. A?rev=query parameter can be added to access a specific revision. -
PUT updates a document. But as described above, the new document body needs to include an
_rev_property that matches the document's current revision (the same property value that came back from a GET), otherwise it'll be rejected as a conflict. -
DELETE deletes a document. Just like a PUT, it needs to supply the current
_revor it'll be rejected.
There's a lot more to the API, from creating databases to accessing special metadata to defining views, but it's largely irrelevant unless you want to use REST directly. If you want to know the details, the API reference on the CouchDB wiki is the best place to dive in (or if you're the toe-dipping type, the aforementioned ]GUIDE covers much of it in tutorial style.)