A REST client
Most services on the internet speak JSON over HTTP. This lesson calls such a service, reads the answer, checks the status, sends data, and handles a server that is not there.
What you will learn#
- what REST means in practice,
- sending
GETandPOSTrequests with a JSON body, - reading the status and the JSON answer,
- timeouts and errors,
- keeping the request code in one helper function.
REST in one minute#
A REST service gives you things (resources) at addresses and lets you use the HTTP methods on them:
| Request | Meaning |
|---|---|
GET /api/books | the list of books |
GET /api/book?id=2 | one book |
POST /api/books + JSON | add a book |
PUT / DELETE | change / remove |
The answers are JSON, and the status code tells whether it worked: 200 OK, 201 Created, 404 Not Found, 500 server error. A good client always looks at the status before it trusts the body.
The program#
For this tutorial the service is started in the same program, so that it needs no internet. The client code is exactly what you would write for a real service: only cUrl would be different.
# a REST client - call a JSON service, read the answer, handle the errors
# (the service is started in the same program so that the tutorial needs no internet)
load "dotnet.ring"
using {
"System.Net.Http"
"System.Text"
"System.Text.Json"
"RingDotNet.Web"
}
oServer = ""
oClient = ""
cUrl = ""
aBooks = [[1,"The Hobbit",1937],[2,"Dune",1965],[3,"Neuromancer",1984]]
func main
# --- the service (a stand-in for a real one on the internet)
oServer = new WebServer("http://127.0.0.1:0")
oServer.onGet("/api/books","listBooks")
oServer.onGet("/api/book","oneBook")
oServer.onPost("/api/books","addBook")
cUrl = oServer.url()
# --- the client
oClient = new HttpClient()
oTimeout = new TimeSpan().FromSeconds(5) # never wait forever for a server
oClient.Timeout = oTimeout
# 1. GET a list: read the JSON array
aAnswer = request("GET","/api/books","")
? "1. GET /api/books -> status " + aAnswer[1]
oDocument = new JsonDocument().Parse(aAnswer[2])
oList = oDocument.RootElement
nLastIndex = oList.GetArrayLength() - 1
for nIndex = 0 to nLastIndex
oBook = oList.Item(nIndex)
? " " + oBook.GetProperty("id").GetInt32() + " " + oBook.GetProperty("title").GetString() + " (" + oBook.GetProperty("year").GetInt32() + ")"
next
oDocument.Dispose()
# 2. GET one item, with a query string
aAnswer = request("GET","/api/book?id=2","")
? nl + "2. GET /api/book?id=2 -> status " + aAnswer[1] + ", body " + aAnswer[2]
# 3. An item that does not exist: the status says so, and the client must look at it
aAnswer = request("GET","/api/book?id=99","")
? nl + "3. GET /api/book?id=99 -> status " + aAnswer[1]
if aAnswer[1] != "OK"
? " the service said: " + aAnswer[2]
ok
# 4. POST new data as JSON
aAnswer = request("POST","/api/books",'{"title":"Foundation","year":1951}')
? nl + "4. POST a new book -> status " + aAnswer[1] + ", body " + aAnswer[2]
aAnswer = request("GET","/api/books","")
? " the list has now " + new JsonDocument().Parse(aAnswer[2]).RootElement.GetArrayLength() + " books"
# 5. A service that is not there: the client raises an error that you catch (and then you tell the user)
try
new HttpClient().GetAsync("http://127.0.0.1:1/").Wait(NULL)
? nl + "5. (unexpected: the call worked)"
catch
? nl + "5. No server at that address: the call raised an error, the program goes on"
done
oServer.close()
# ---------------------------------------------------------------- the service
func listBooks oRequest
aList = []
for aBook in aBooks
aList + [["id",aBook[1]],["title",aBook[2]],["year",aBook[3]]]
next
return webJson(aList)
func oneBook oRequest
nId = number(oRequest.query("id"))
for aBook in aBooks
if aBook[1] = nId
return webJson([["id",aBook[1]],["title",aBook[2]],["year",aBook[3]]])
ok
next
return [404,"text/plain","no book " + nId]
func addBook oRequest
oDocument = new JsonDocument().Parse(oRequest.body())
oRoot = oDocument.RootElement
nId = len(aBooks) + 1
aBooks + [nId,oRoot.GetProperty("title").GetString(),oRoot.GetProperty("year").GetInt32()]
oDocument.Dispose()
return [201,"application/json",'{"id":' + nId + '}']
# ---------------------------------------------------------------- the client's helper: send, wait, return [status, body]
func request cMethod, cPath, cBody
oMessage = new HttpRequestMessage().@New([ :method = new HttpMethod(cMethod), :requestUri = cUrl + cPath ])
if cBody != ""
oContent = (new StringContent).@New([ :content = cBody, :encoding = new Encoding().UTF8, :mediaType = "application/json" ])
oMessage.Content = oContent
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]1. GET /api/books -> status OK
1 The Hobbit (1937)
2 Dune (1965)
3 Neuromancer (1984)
2. GET /api/book?id=2 -> status OK, body {"id":2,"title":"Dune","year":1965}
3. GET /api/book?id=99 -> status NotFound
the service said: no book 99
4. POST a new book -> status Created, body {"id":4}
the list has now 4 books
5. No server at that address: the call raised an error, the program goes onThis program uses a generic function (dnNew) where a class cannot be used. The lesson The generic functions explains them.
How it works#
One helper for all requests#
request(method, path, body) builds the request, sends it, waits and returns [status, body]. Everything else calls it. A request is an HttpRequestMessage created with named arguments: [ :method = new HttpMethod(cMethod), :requestUri = cUrl + cPath ]. For a POST the body is a StringContent with the text, the encoding (UTF8) and the media type application/json, which tells the server how to read it.
The Task pattern#
SendAsync returns a Task at once; Wait(NULL) waits for the answer; .Result is the HttpResponseMessage. Reading the body is again asynchronous (ReadAsStringAsync). Here, because the server lives in the same program, the helper calls serveOne while it waits; with a real server on the internet you would just wait.
Reading JSON#
Step 1 parses the array with JsonDocument: GetArrayLength(), Item(i), and for each book GetProperty("title").GetString() and GetProperty("year").GetInt32(). Call Dispose() on the document when you are done (the tutorial JSON and XML).
Status first#
Step 3 asks for a book that does not exist. The status is NotFound and the body is a message, not JSON. If the client had tried to parse the body as JSON it would have failed. Check the status, then read the body.
Sending data#
Step 4 posts {"title":"Foundation","year":1951}. The service answers 201 Created with the new id, and the list has four books.
Timeouts and errors#
oClient.Timeout = new TimeSpan().FromSeconds(5) stops waiting after five seconds: without a timeout a dead server can block your program for minutes. Step 5 calls an address where nobody listens; the call raises an error, and the try / catch turns it into a message for the user. Real programs also retry after a pause and tell the user in plain words ("The service is not available, try again later").
What you learned#
- GET and POST with JSON,
- status before body,
Task+Wait+Result,- timeouts and catching network errors,
- one request helper.
Exercises#
- Add
deleteBook(nId)using theDELETEmethod (and a handler on the service). - Retry a failed request up to three times with a pause (
Thread.Sleep). - Add an
Acceptheader (oClient.DefaultRequestHeaders.Add(...)). - Call a real public API (for example a free JSON placeholder service) and print three fields. You need internet for this one.