Cloudant Fundamentals: Programmatic CRUD

Friendly syntax for Node.js, Python, and Java (part 6 of 10)


In the previous two posts we saw how how the command-line tool curl is all that is required to do basic read and write operations with Cloudant, and how two API calls can be used for bulk commands.

In this post we’ll look at equivalent tasks using programmatic means.

You don’t need a special library to work with Cloudant — just something capable of making HTTP requests. The libraries do help, however, with authentication and parameter encoding. There are three officially supported libraries for three programming languages:

For these examples I’m going to use the cloudant-quickstart library that makes it easy for you to get started with Cloudant. It is installed by simply typing npm install cloudant-quickstart into your terminal.

You can copy the following code snippets into either:

  1. a Node “REPL” (just type node on the command line)
  2. a Jupyter notebook using the pixiedust_node library
  3. a text file
Photo by Max Nelson on Unsplash

Connect to the database

First we need a URL containing our Cloudant credentials and to start up the library:

Create the database

Creating a database is as simple as calling the create function:

Creating documents

Let’s say we want to add an array of documents to our database:

The insert document can be used to write them to the database:

The same goes for single documents:

Reading documents

Documents can be read back singly by specifying the ID of the document you want:

You may also specify a list of ids:

Or ask for all the documents:

Updating documents

The cloudant-quickstart library allows documents to be updated without worrying about revision tokens: just pass in the new document body and the library will figure it out:

The library will even allow you to make incremental updates to documents by passing the document id, an object containing the changes, and true (to indicate that the updates are to be merged in) as three parameters to the update function:

Deleting a document

A documents can be removed from the database by passing an ID delete function:

Where did the rev token go?

The cloudant-quickstart library hides the rev token from you. The rev token is a tricky concept for new starters, so this library abstracts it from you so that you can get on with building something quickly. In a production environment, you will have to get to grips with revision tokens, but for now we can sit back and relax.

Next time

In the next post we’ll look at querying data. Until then!