RingDotNetfor Ring

A web service with a database

Put the ideas of the last tutorials together: a web service that stores notes in a database and speaks JSON, with a client that uses it.

What you will learn#

The design#

A REST-style API uses the HTTP method to say what to do and the address to say what to do it with:

RequestMeaningAnswer
GET /noteslist the notes200 and a JSON array
POST /notes (the text is the body)add a note201 and the new id, or 400 if the text is empty
DELETE /notes?id=1delete a note200, or 404 if there is no such note

The program#

samples/UsingDotNet/tutorials/ch07_notes_service.ring
# a web service with a database - JSON over HTTP, stored with Entity Framework
load "dotnet.ring"

using {
	"System.Net.Http"
	"RingDotNet.Web"
	"RingDotNet.Data"
}

oServer = ""
oClient = ""
cUrl = ""
oDb = ""

func main

	# 1. The database: one table, kept in memory for this tutorial (use "Data Source=notes.db" for a file)
	oDb = new RingDatabase("Data Source=:memory:",[
		["Notes",[["Id","int",1],["Text","string",0,[["required",1],["maxlength",200]]],["Done","int",0,[["default",0]]]]]
	])

	# 2. The web service: each address is a Ring function
	oServer = new WebServer("http://127.0.0.1:0")
	oServer.onGet("/notes","listNotes")
	oServer.onPost("/notes","addNote")
	oServer.onDelete("/notes","deleteNote")
	cUrl = oServer.url()

	# 3. A client uses the service (the same program, so that you can see the whole conversation)
	oClient = new HttpClient()
	? "POST /notes   -> " + send("POST","/notes","Buy milk")
	? "POST /notes   -> " + send("POST","/notes","Learn Ring and .NET")
	? "POST /notes   -> " + send("POST","/notes","")
	? "GET  /notes   -> " + send("GET","/notes","")
	? "DELETE        -> " + send("DELETE","/notes?id=1","")
	? "GET  /notes   -> " + send("GET","/notes","")
	? "DELETE (nothing)-> " + send("DELETE","/notes?id=99","")
	oServer.close()
	oDb.close()

# ---------------------------------------------------------------- the handlers

func listNotes oRequest

	aList = []
	aRows = oDb.all("Notes")
	for aRow in aRows
		aList + [["id",dbValue(aRow,"Id")],["text",dbValue(aRow,"Text")]]
	next
	return webJson(aList)

func addNote oRequest

	cText = trim(oRequest.body())
	if cText = ""
		return [400,"text/plain","The text of the note is empty"]
	ok
	nId = oDb.insert("Notes",[["Text",cText]])
	return [201,"application/json",'{"id":' + nId + '}']

func deleteNote oRequest

	nId = number(oRequest.query("id"))
	if oDb.remove("Notes",nId) = 0
		return [404,"text/plain","There is no note " + nId]
	ok
	return [200,"text/plain","deleted " + nId]

# ---------------------------------------------------------------- the client

func send cMethod, cPath, cBody

	oMessage = new HttpRequestMessage().@New([ :method = new HttpMethod(cMethod), :requestUri = cUrl + cPath ])
	if cBody != ""
		oMessage.Content = new StringContent(cBody)
	ok
	oTask = oClient.SendAsync(oMessage)
	for nTry = 1 to 50
		if oServer.serveOne(100)
			exit
		ok
	next
	oTask.Wait(NULL)
	oResponse = oTask.Result
	oBody = oResponse.Content.ReadAsStringAsync(NULL)
	oBody.Wait(NULL)
	return oResponse.StatusCode + " " + oBody.Result
Output
POST /notes   -> Created {"id":1}
POST /notes   -> Created {"id":2}
POST /notes   -> BadRequest The text of the note is empty
GET  /notes   -> OK [{"id":1,"text":"Buy milk"},{"id":2,"text":"Learn Ring and .NET"}]
DELETE        -> OK deleted 1
GET  /notes   -> OK [{"id":2,"text":"Learn Ring and .NET"}]
DELETE (nothing)-> NotFound There is no note 99

How it works#

Two start-up calls#

"RingDotNet.Web" in the using block starts the web runtime and "RingDotNet.Data" loads Entity Framework. Both before any other .NET call.

The database#

A RingDatabase with a table Notes: a numbered key Id, a required Text (at most 200 characters), and a Done flag with a default of 0. "Data Source=:memory:" keeps the data in memory, which is perfect for a tutorial; use "Data Source=notes.db" for a file. See the tutorial Databases step by step.

The handlers#

Each handler is a Ring function that receives the request and returns the response.

Note

The handlers use oDb, a global variable, because they run later, from the web server. Remember: code that Ring runs for .NET sees only globals.

The client#

send builds an HttpRequestMessage with a method and an address (named arguments again: [ :method = ..., :requestUri = ... ]), sends it, lets the server handle it with serveOne, and reads the response. In a real client program the server runs somewhere else and you never call serveOne.

Errors become responses#

Nothing in a handler ends the program: a bad request gets 400, a missing note 404. If a handler raises an error, the server answers 500 with the message, and keeps running.

What you learned#

Exercises#

  1. Add PUT /notes?id=1 that marks a note as done (update).
  2. Add GET /notes?id=2 that returns one note, or 404.
  3. Make the server serve an HTML page at / that lists the notes, as the WebApi application does.
  4. Switch to a file database and restart the program: are the notes still there?

Next#

A small web site

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.