Posts Tagged “rest”

Tuesday, December 7, 2021
  A Tour of myPrayerJournal v3: Conclusion

NOTE: This is the final post in a series; see the introduction for information on requirements and links to other posts in the series.

We've gone in depth on several different aspects of this application and the technologies it uses. Now, let's zoom out and look at some big-picture lessons learned.

What I Liked

Generally speaking, I liked everything. That does not make for a very informative post, though, so here are a few things that worked really well.

Simplification Via htmx

One of the key concepts in a Representational State Transfer (REST) API is that of Hypermedia as the Engine of Application State (HATEOAS). In short, this means that the state of an application is held within the hypermedia that is exchanged between client and server; and, in practice, the server is responsible for altering that state. This is completely different from the JSON API / JavaScript framework model, even if they use GET, POST, PUT, and PATCH properly.

(This is a near over-simplification; the paper that initially proposed these concepts – in much, much more detail – earned its author a doctoral degree.)

The simplicity of this model is great; and, when I say “simplicity,” I am speaking of a lack of complexity, not a naïveté of approach. I was able to remove a large amount of complexity and synchronization from the client/server interactions between myPrayerJournal v2 and v3. State management used to be the most complex part of the application. Now, the most complex part is the HTML rendering; since that is what controls the state, though, this makes sense. I have 25 years of experience writing HTML, and even at its most complex, it simply is not.

LiteDB

This was a very simple application - and, despite its being open for any user with a Google or Microsoft account, I have been the only regular user of the application. LiteDB's setup was easy, implementation was easy, and it performs really well. I suspect this would be the case with many concurrent users. If the application were to grow, and I find that my suspicion was not borne out by reality, I could create a database file per user, and back up the data directory instead of a specific file. As with htmx, the lack of complexity makes the application easily maintainable.

What I Learned

Throughout this entire series of posts, most of the content would fall under this heading. There are a few things that did not fit into those posts, though.

htmx Support in .NET

I developed Giraffe.Htmx as a part of this effort, and mentioned that I became aware of htmx on an episode of .NET Rocks!. The project I developed is very F#-centric, and uses features of the language that are not exposed in C# or VB.NET. However, there are two packages that work with the standard ASP.NET Core paradigm. Htmx provides server-side support for the htmx request and response headers, similar to Giraffe.Htmx, and Htmx.TagHelpers contains tag helpers for use in Razor, similar to what Giraffe.ViewEngine.Htmx does for Giraffe View Engine. Both are written by Khalid Abuhakmeh, a developer advocate at JetBrains (which generously licensed their tools to this project, and produces the best developer font ever).

While I did not use these projects, I did look at the source, and they look good. Open source libraries go from good to great by people using them, then providing constructive feedback (and pull requests, if you are able).

Write about Your Code

Yes, I'm cheating a bit with this one, as it was one of the takeaways from the v1 tour, but it's still true. Writing about your code has several benefits:

  • You understand your code more fully.
  • Others can see not just the code you wrote, but understand the thought process behind it.
  • Readers can provide you feedback. (This may not always seem helpful; regardless of its tone, though, thinking through whether the point of their critique is justified can help you learn.)

And, really, knowledge sharing is what makes the open-source ecosystem work. Closed / proprietary projects have their place, but if you do something interesting, write about it!

What Could Be Better

Dove-tailing from the previous section, writing can also help you think through your code; if you try to explain it, and and have trouble, that should serve as a warning that there are improvements to be had. These are the areas where this project has room to get better.

Deferred Features

There were 2 changes I had originally planned for myPrayerJournal v3 that did not get accomplished. One is a new “pray through the requests” view, with a distraction-free next-card-up presentation. The other is that updating requests sends them to the bottom of the list, even if they have not been marked as prayed; this will require calculating a separate “last prayed” date instead of using the “as of” date from the latest history entry.

The migration introduced a third deferred change. When v1/v2 ran in the browser, the dates and times were displayed in the user's local timezone. With the HTML being generated on the server, though, dates and times are now displayed in UTC. The purpose of the application is to focus the user's attention on their prayer requests, not to make them have to do timezone math in their head! htmx has an hx-headers attribute that specifies headers to pass along with the request; I plan to use a JavaScript call to set a header on the body tag when a full page loads (hx-headers is inherited), then use that timezone to adjust it back to the user's current timezone.

That LiteDB Mapping

I did a good bit of tap-dancing in the LiteDB data model and mapping descriptions, mildly defending the design decisions I had made there. The recurrence should be designed differently, and there should be individual type mappings rather than mapping the entire document. Yes, it worked for my purpose, and this project was more about Vue to htmx than ensuring a complete F#-to-LiteDB mapping of domain types. As I implement the features above, though, I believe I will end up fixing those issues as well.


Thank you for joining me on this tour; I hope it has been enjoyable, and maybe even educational.

Categorized under , , , , ,
Tagged , , , , , , , , , , , , , , , , , ,

Wednesday, August 29, 2018
  A Tour of myPrayerJournal: The API

NOTES:

  • This is post 4 in a series; see the introduction for all of them, and the requirements for which this software was built.
  • Links that start with the text “mpj:” are links to the 1.0.0 tag (1.0 release) of myPrayerJournal, unless otherwise noted.

Now that we have a wonderful, shiny, reactive front end, we need to be able to get some data into it. We'll be communicating via JSON between the app and the server. In this post, we'll also attempt to explain some about the F# language features used as part of the API.

The Data

The entities are defined in Data.fs (mpj:Data.fs). We'll dig into them more fully in the “data store” post, but for now, we'll just focus on the types and fields. We have four types: History (lines 33-39), Note (lines 67-71), Request (lines 94-110), and JournalRequest (lines 153-173). A Request can have multiple Notes and History entries, and JournalRequest is based on a view that pulls these together and computes things like the current text of the request and when it should be displayed again.

We apply no special JSON transformations, so the fields in these record types are the properties in the exported JSON.

The URLs

To set the API apart from the rest of the URLs, they all start with /api/. Request URLs generally follow the form request/[id]/[action], and there is a separate URL for the journal. Line 54 in Program.fs (mpj:Program.fs) has the definition of the routes. We used Giraffe's Token Router instead of the traditional one, as we didn't need to support any URL schemes it doesn't. The result really looks like a nice, clean “table of contents” for the routes support by the API.1

We aren't done with routes just yet, though. Let's take a look at that notFound handler (mpj:Handlers.fs); it's on line 27. Since we're serving a SPA, we need to return index.html, the entry point of the SPA, for URLs that belong to it. Picture a user sitting at https://prayerjournal.me/journal and pressing “Refresh;” we don't want to return a 404! Since the app has a finite set of URL prefixes, we'll check to see if one of those is the URL. If it is, we send the Vue app; if not, we send a 404 response. This way, we can return true 404 responses for the inevitable hacking attempts we'll receive (pro tip, hackers - /wp-admin/wp-upload.php does not exist).

Defining the Handlers

Giraffe uses the term “handler” to define a function that handles a request. Handlers have the signature HttpFunc -> HttpContext -> Task<HttpContext option> (aliased as HttpHandler), and can be composed via the >=> (“fish”) operator. The option part in the signature is the key in composing handler functions. The >=> operator creates a pipeline that sends the output of one function into the input of another; however, if a function fails to return a Some option for the HttpContext parameter, it short-circuits the remaining logic.2

The biggest use of that composition in myPrayerJournal is determining if a user is logged in or not. Authorization is also getting its own post, so we'll just focus on the yes/no answer here. The authorized handler (line 71) looks for the presence of a user. If it's there, it returns next ctx, where next is the next HttpFunc and ctx is the HttpContext it received; this results in a Task<HttpContext option> which continues to process, hopefully following the happy path and eventually returning Some. If the user is not there, though, it returns the notAuthorized handler, also passing next and ctx; however, if we look up to line 67 and the definition of the notAuthorized handler, we see that it ignores both next and ctx, and returns None. However, notice that this handler has some fish composition in it; setStatusCode returns Some (it has succeeded) but we short-circuit the pipeline immediately thereafter.

We can see this in use in the handler for the /api/journal endpoint, starting on line 137. Both authorize and the inline function below it have the HttpHandler signature, so we can compose them with the >=> operator. If a user is signed in, they get a journal; if not, they get a 403.

When a handler is expecting a parameter from a route, the handler's signature is a bit different. The handler for /api/request/[id], on line 246, has an extra parameter, reqId. If we look back in Program.fs line 64, we see where this handler is assigned its route; and, if you compare it to the route for /api/journal on line 59, you'll see that it looks the same. The difference here is the expectations of route (for the journal) vs. routef (for the request). route expects no parameter, but routef will extract the parameters, Printf style, and pass them as parameters that precede the HttpHandler signature.

Executing the Handlers

myPrayerJournal has GET, POST, and PATCH routes defined. We'll look at representative examples of each of these over the next few paragraphs.

For our GET example, let's return to the Request.get handler, starting on line 246. Once we clear the authorize hurdle, the code attempts to retrieve a JournalRequest by the request ID passed to the handler and the user ID passed as part of the request. If it exists, we return the JSON representation of it; if not, we return a 404. Note the order of parameters to the json result handler - it's json [object] next ctx (or json [object] HttpHandler). We also defined an asJson function on line 75; this flips the parameters so that the output object is the last parameter (asJson next ctx [object]), enabling the flow seen in the journal handler on line 137.

For our POST example, we'll use Request.addNote, starting on line 218. It checks authorization, and to make sure the request exists for the current user. If everything is as it should be, it then uses Giraffe's BindJsonAsync<'T> extension method to create an instance of the expected input form. Since the handler doesn't have a place to specify the expected input object, this type of model binding cannot happen automatically; the upside is, you don't waste CPU cycles trying to do it if you don't need it. Once we have our model bound, we create a new Note, add it, then return a 201 response.

PATCH handlers are very similar; Request.snooze is one such handler, starting on line 291. The flow is very similar as the one for Request.addNote, except that we're updating instead of adding, and we return 204 instead of 201.

Configuring the Web Server

Giraffe enables Suave-like function composition on top of Kestrel and the ASP.NET Core infrastructure. Rather than using the Startup class, myPrayerJournal uses a functional configuration strategy. The calls are in Program.fs starting on line 115; there are lots of other guides on how to configure ASP.NET Core, so I won't say too much more about it.

Notice, though, line 31. Earlier, we discussed the >=> operator and how it worked. This is an example of the >> composition operator, which is part of F#. For functions whose output can be run directly into the next function's input, the >> operator allows those functions to be composed into a single function. If we were to look at the signature of the composed function within the parentheses, its signature would be string -> unit; so, we pass the string “Kestrel” to it, and it runs through and returns unit, which is what we expect for a configuration function. Here's how that breaks down:

  • ctx.Configuration.GetSection's signature is string -> IConfigurationSection
  • opts.Configure's signature is IConfiguration -> KestrelConfigurationLoader (IConfigurationSection implements IConfiguration)
  • ignore's signature is 'a -> unit

If this still doesn't make sense, perhaps this will help. The Configure.kestrel function could also have been written using the |> piping operator instead, with the equivalent code looking like:

  let kestrel (ctx : WebHostBuilderContext) (opts : KestrelServerOptions) =
    ctx.Configuration.GetSection "Kestrel"
    |> opts.Configure
    |> ignore

 

That concludes our tour of the API for now, though we'll be looking at it again next time, when we take a deeper dive into authentication and authorization using Auth0.


1 While we tried to follow REST principles in large part, the REST purists would probably say that it's not quite RESTful enough to claim the name. But, hey, we do use PATCH, so maybe we'll get partial credit…

2 Scott Wlaschin has a great post entitled “Railway Oriented Programming” that explains this concept in general, and the fish operator specifically. Translating his definition to Giraffe's handlers, the first function is switch1, the next parameter is switch2, and the HttpContext is the x parameter; instead of Success and Failure, the return type utilizes the either/or nature of an option being Some or None. If you want to understand what makes F# such a great programming model, you'll spend more time on his site than on The Bit Badger Blog.

Categorized under , ,
Tagged , , , , , , , , , , , , , , , , , , ,

Sunday, June 17, 2012
  40/40 Web Service for 2012

Back in 2010, we wrote a web service for the 40/40 Prayer Vigil organized by the Ethics and Religious Liberty Commission of the Southern Baptist Convention. This allowed us to use the content in multiple places. They are doing another vigil this year, but the service we wrote two years ago was not terribly reusable.

This year, we have developed a reusable web service that should hold up for 2014 and beyond. (Acronym alert - non-programmers skip the next sentence.) This one has a REST API instead of SOAP and WSDL, and supports XML, JSON, and HTML output formats. This year, it also supports both English and Español.

The REST API start page is at this URL no longer active. The prayer guides require an output format, a language, the Scripture version, whether the guide is for a day or an hour, and the day or hour number. There are lookup transactions for lists of available output formats, languages, and Scripture versions, and lookups for converting a date to a day number and a date/time to an hour number.

There will be a WordPress plug-in shortly that will utilize this to display the current day or hour's prayer guide directly on your blog; we'll make another post when that is available. Also, starting September 26th (the first day of the vigil), it will be available for display with no login required at the Hoffmantown Prayer and PrayerTracker websites. Developers, the service is available now; if you want to write code to utilize the service, you've got 3 months to make it work!

Categorized under
Tagged , , , , , , , , , , , , ,