Endpoint: HTTP Get
Our first task is simple:
If client access SERVER_URL/authors
, it will Get
a list of authors. Note that SERVER_URL
for now is port 7000
on localhost (http://127.0.0.1:7000/
) on your computer.
Here is a code:
Each of the above get
function calls defines an api endpoint and is called a route.
info
We will use JSON to transfer data between server and client so "the list of authors" will be a JSON Array.
Get set up!
In addition to starting the (local) server we must the MyBooksApp database and the Authors
table, specifically, into our author Data Access Object (i.e. AuthorsDao
). That is what we did with:
Note the call to the helper method getSql2o()
to get a new instance of Sql2o to the MyBooksApp
database.
Here is the implemetation of getSql2o
helper method:
We pass the Sql2o
object that this helper method returns to the constructor of the Sql2oAuthorDao
class.
caution
In order for the above code to work, the MybooksApp
database should exist with a valid Authors
table in it (and ideally some rows in the table). For more info on how to create a databse and tables, and insert rows into them, refer to the previous readings under Persistence with Databases section.
Once we have the list of authors from the Authors
table, we use the toJson
method of Gson
to convert them into a JSON array of authors and store
them into a string. We covered JSON and Gson here.
Next, we need to set the content type of our http response as well as the response status. Since we are returning the data in JSON format, we set it accordingly, and we also set the status to 200
to indicate success:
Eventually, we return the results
.
HTTP content type and statuses
You can see a full list of different MIME types here. Also, the following table shows different http status codes and their meaning:
Status | Meaning |
---|---|
200 (OK) | This is the standard response for successful HTTP requests. |
201 (CREATED) | This is the standard response for an HTTP request that resulted in an item being successfully created. |
204 (NO CONTENT) | This is the standard response for successful HTTP requests, where nothing is being returned in the response body. |
400 (BAD REQUEST) | The request cannot be processed because of bad request syntax, excessive size, or another client error. |
403 (FORBIDDEN) | The client does not have permission to access this resource. |
404 (NOT FOUND) | The resource could not be found at this time. It is possible it was deleted, or does not exist yet. |
500 (INTERNAL SERVER ERROR) | The generic answer for an unexpected failure if there is no more specific information available. |
If you run the application and point your browser to http://127.0.0.1:7000/authors
, you must see a list of authors in JSON array format, something like:
tip
You can use a browser extension like JSON Formatter to prettify the output into a more readable one.