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 shape of a small web API (
GETlist,POSTadd,DELETEremove), - storing data with
RingDatabasefrom a web handler, - answering with JSON and the right status codes,
- validating a request.
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:
| Request | Meaning | Answer |
|---|---|---|
GET /notes | list the notes | 200 and a JSON array |
POST /notes (the text is the body) | add a note | 201 and the new id, or 400 if the text is empty |
DELETE /notes?id=1 | delete a note | 200, or 404 if there is no such note |
The program#
# 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.ResultPOST /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 99How 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.
listNotesreads every row withoDb.all("Notes"), converts each to a list of[name, value]pairs and returnswebJson(aList).webJsonturns pairs into JSON objects:{"id":1,"text":"Buy milk"}.addNotereads the body, answers[400, ...]when it is empty, otherwise inserts and returns[201, "application/json", ...]with the new id.deleteNotereads the query value (oRequest.query("id")), removes the row, and answers404whenremovereturns0.
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#
- methods + addresses + status codes make an API,
- handlers use the database and return JSON,
- validate input and answer with the right status,
- globals for what handlers need.
Exercises#
- Add
PUT /notes?id=1that marks a note as done (update). - Add
GET /notes?id=2that returns one note, or404. - Make the server serve an HTML page at
/that lists the notes, as the WebApi application does. - Switch to a file database and restart the program: are the notes still there?