CRUD-Operations in RavenDB (HTTP API)

RavenDB is not only useful when you have a .Net project. When you can send a HTTP-Request you have all you need. The HTTP API provides all of the daily used commands in a web friendly way. There are however some commands that are not fully supported. Should you need them you can always fall back to the RavenDB Studio and execute them there.

This post is part of the RavenDB series. You can find the other parts here:

 

Necessary Preparations

To try the HTTP API I use curl. This is a command line tool build to transfer data with an URL syntax. You can use it to test everything that has an URL as an endpoint. In your project you will use the build in command to post data to an URL, like $http.get() in AngularJS. But as long as you test the API curl is very helpful.

Since HTTP does know nothing about types all the data that is transferred is just a string. Therefore all we need to represent a book class is this JSON snippet:

 

Saving a Book

To save the snipped we only need a running RavenDB instance, a console (like cmd or console 2) and this curl command:

Using this command we have to define the ID on our own and the URL must point to the correct collection. If there is another document with the same URL it gets overwritten.

When we want RavenDB to generate the ID and we don’t care in which collection the document is stored we can use the POST command on the document collection:

All we need with the HTTP API is a URL, the Document and the appropriate HTTP method. There is no DocumentStore, no session and no call to SaveChanges(). The commands are much simpler, but you don’t have the Unit of Work Pattern at your disposal.

 

Reading the Book

To read a specific book we can use its primary key as part of the URL:

 

Changing the Book

To change an object we need to replace the old value with the new one (we SET a new value):

When we need to replace the whole book we can just add another book at the same URL:

 

Deleting the Book

To end the lifecycle of our book we have to delete it with the DELETE method:

 

Next

Using a NoSQL database doesn’t mean we no longer have to handle related data. That’s why we will find out next time how we can structure our documents and how relations can be expressed.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.