A JSON API
A server that answers with JSON and a client that reads it with Jackson, in one program.
What you will learn#
- routes that answer with
jWebJson, - a
404answer that is JSON too, jHttpGetand Jackson'sreadTreeto read what the server said.
The program#
# Tutorial 28: a JSON API - the server answers with JSON and the client reads it with Jackson (the jar comes from Maven Central the first time)
load "java.ring"
jMavenClasses("com.fasterxml.jackson.core:jackson-databind:2.17.0",["com.fasterxml.jackson.databind","com.fasterxml.jackson.databind.node"])
using {
"com.fasterxml.jackson.databind"
}
# 1. a server with two routes that answer with JSON
oServer = new JavaWebServer(0)
oServer.onGet("/api/books","books")
oServer.onGet("/api/books/:id","oneBook")
cBase = oServer.url()
# 2. the client gets the JSON text
aAnswer = jHttpGet(cBase + "/api/books")
? aAnswer[2]
# 3. Jackson reads the text: readTree gives a tree of nodes
oMapper = new ObjectMapper
oTree = oMapper.readTree(aAnswer[2])
? "books: " + oTree.@get("books").size()
for nAt = 0 to oTree.@get("books").size() - 1
oBook = oTree.@get("books").@get(nAt)
? oBook.@get("title").asText(NULL) + " (" + oBook.@get("year").asInt(NULL) + ")"
next
# 4. one book, and a book that is not there
oOne = oMapper.readTree(jHttpGet(cBase + "/api/books/2")[2])
? "book 2: " + oOne.@get("title").asText(NULL)
aMissing = jHttpGet(cBase + "/api/books/9")
? "" + aMissing[1] + " " + aMissing[2]
oServer.close()
func bookList
return [
[["id",1],["title","The Hobbit"],["year",1937]],
[["id",2],["title","Dune"],["year",1965]],
[["id",3],["title","Neuromancer"],["year",1984]]
]
func books oRequest
return jWebJson([["books",bookList()]])
func oneBook oRequest
for aBook in bookList()
if aBook[1][2] = 0 + oRequest.param("id")
return jWebJson(aBook)
ok
next
return [404,"application/json",jJsonText([["error","no such book"]])]{"books":[{"id":1,"title":"The Hobbit","year":1937},{"id":2,"title":"Dune","year":1965},{"id":3,"title":"Neuromancer","year":1984}]}
books: 3
The Hobbit (1937)
Dune (1965)
Neuromancer (1984)
book 2: Dune
404 {"error":"no such book"}How it works#
jWebJson turns a list of [name, value] pairs into a JSON object and any other list into an array, so the same Ring lists describe the data on both sides. Jackson is used only by the client, to read the answer; the server needs no package. The first run downloads the Jackson jars from Maven Central.
Exercises#
- Add a route that creates a book with a POST.
- Print the books sorted by year with
jQuery. - Read the answer with Jackson's
at("/books/0/title").