
Time for action — creating a CouchDB document
In this exercise, we'll create a document by initiating a POST
call. You'll notice that our curl
statement will start to get a bit more complex.
- Create a document in the
test-db
database by running the following command in Terminal:curl -X POST -H "Content-Type:application/json" -d '{"type": "customer", "name":"Tim Juravich", "location":"Seattle, WA"}' http://localhost:5984/test-db
- Terminal will respond with something similar to the following:
{"ok":true,"id":"39b1fe3cdcc7e7006694df91fb002082","rev":"1-8cf37e845c61cc239f0e98f8b7f56311"}
- Let's retrieve the newly created document from CouchDB. Start by copying the ID you were returned at the last response of the Terminal to your clipboard; mine is
39b1fe3cdcc7e7006694df91fb002082
, but yours will be different. Then run this command in Terminal, pasting your ID at the end of the URL:curl -X GET http://localhost:5984/test-db/41198fc6e20d867525a8faeb7a000015 | python -mjson.tool
- Terminal will respond with something similar to the following:
{ "_id": "41198fc6e20d867525a8faeb7a000015", "_rev": "1-4cee6ca6966fcf1f8ea7980ba3b1805e", "location": "Seattle, WA", "name": "Tim Juravich", "type:": "customer" }
What just happened?
We used Terminal to trigger a POST
call to CouchDB's RESTful JSON API. This time, our curl
statement gained some more options that we haven't used before. The -H
option enables us to set the header of the HTTP request for POST
methods. We need to set the content-type
to JSON so that CouchDB's RESTful API knows what format is coming in. We also used a new option, -d
option, which stands for data. The data option allows us to pass data in the form of a string along with our curl
statement.
After creating our document, we retrieved it to Terminal by submitting a GET
request to http://localhost:5984/test-db/41198fc6e20d867525a8faeb7a000015
. In response, we received a JSON object containing all of the document's data. At the end of this request, we did something a little different. We added python mjson.tool
, which is a built-in component from Python that enables us to nicely format our JSON responses, so that we can make more sense of them. This will come in handy as we start looking at more complex documents.
Note
I didn't mention that you needed Python installed earlier in the book because this is a nice to have feature. If you receive an error because you are missing Python, you can either install it by going here: http://python.org/download/.
I know that this has been a bit tiresome, but curl
will be the main method that our PHP code will use to talk to CouchDB, so it's important that we're familiar with how it works. Luckily, there is an easier way to access and manage your data through a tool named Futon.