Implement fast, type-safe HTTP webservices for Finagle
Scala CSS HTML Shell
Permalink
Failed to load latest commit information.
argonaut/src deprecated Body.apply and Path.apply methods in favour of .of() alter… Feb 22, 2017
circe/src deprecated Body.apply and Path.apply methods in favour of .of() alter… Feb 22, 2017
core/src deprecated Body.apply and Path.apply methods in favour of .of() alter… Feb 22, 2017
gson/src added missing number method for double, and fixed #32 Jan 7, 2017
handlebars/src refactor of template system to DRY it out Jul 2, 2016
jackson/src deprecated Body.apply and Path.apply methods in favour of .of() alter… Feb 22, 2017
json4s/src deprecated Body.apply and Path.apply methods in favour of .of() alter… Feb 22, 2017
msgpack/src deprecated Body.apply and Path.apply methods in favour of .of() alter… Feb 22, 2017
mustache/src can't use JavaConverters in scala 2.11 Jan 19, 2017
play/src deprecated Body.apply and Path.apply methods in favour of .of() alter… Feb 22, 2017
project add coursier Feb 8, 2017
spray/src refix #32, as test was incorrect (ints only used 1 and 10 was being r… Jan 7, 2017
src deprecated Body.apply and Path.apply methods in favour of .of() alter… Feb 22, 2017
tools dave - added script to upgrade version numbers of MD files Jan 30, 2016
.gitattributes Create .gitattributes Jan 22, 2017
.gitignore dave - added start of site Jan 25, 2016
.travis.yml upgrade to 2.12.1 Feb 4, 2017
CHANGELOG.md deprecated Body.apply and Path.apply methods in favour of .of() alter… Feb 22, 2017
CONTRIBUTING.md fix docs Jul 23, 2016
LICENSE dave - added start of new project. Mar 1, 2015
README.md deprecated Body.apply and Path.apply methods in favour of .of() alter… Feb 22, 2017
bower.json added clipboard Jan 14, 2017
build.sbt deprecated Body.apply and Path.apply methods in favour of .of() alter… Feb 22, 2017
buildWithCoverage.sh coverage Jun 23, 2016
fintrospect.iml dave - started adding body parameters. Apr 3, 2015
harp.json deprecated Body.apply and Path.apply methods in favour of .of() alter… Feb 22, 2017
package.json dave - site changes Jan 28, 2016
publish.sh publish all versions Jan 19, 2017
publish_site.sh 2.12. script Feb 4, 2017
sbt daveD - remove PermSize from SBT file May 31, 2015
upgrade.sh more changes for v13 cutover Jun 24, 2016

README.md

Fintrospect                       

Fintrospect is a library that adds an intelligent HTTP routing layer to the Finagle RPC framework from Twitter. Via a shared contract, it provides a simple way to implement both webservice endpoints and HTTP clients which are:

  • Type-safe : auto-marshals request parameters/bodies into the correct primitive and custom types.
  • Auto-validating : enforce the correctness of required/optional request parameters/bodies, generating a BadRequest if the contract is broken.
  • Auto-documenting : runtime generation of endpoint documentation such as Swagger JSON or web sitemap XML. Generates JSON Schema for example object formats to be included in these API docs.
  • Uniform : reuse the same contract to define both server endpoints and HTTP clients This also allows extremely low effort fake servers to be created

Additionally, Fintrospect provides a number of mechanisms to leverage these routes:

  • Easily build type-safe HTTP responses with a set of custom builders for a wide variety of message formats:
    • JSON: Argo, Argonaut, Circe, GSON, Jackson, Json4S, Play JSON, Spray JSON
      • Auto-marshaling of case classes instances to/from JSON (for Argonaut/Circe/Json4S/Play).
      • Implement simple PATCH/PUT endpoints of case class instances (Circe only).
    • Native implementations of XML, Plain Text, HTML, XHTML
    • MsgPack binary format
  • Serve static content from the classpath or a directory
  • Template View support (with Hot-Reloading) for building responses with Mustache or Handlebars
  • Anonymising headers for dynamic-path based endpoints, removing all dynamic path elements. This allows, for example, calls to particular endpoints to be grouped for metric purposes. e.g. /search/author/rowling becomes /search/author/{name}
  • Interacts seamlessly with other Finagle based libraries, such as Finagle OAuth2
  • Utilities to help you unit-test endpoint services and write HTTP contract tests for remote dependencies

Get it

Fintrospect is intentionally dependency-lite by design - other than Finagle, the core library itself only has a single non org.scala dependency. No dependency on Scalaz, Cats or Shapeless, so there are no compatibility headaches.

To activate the extension library features (JSON, templates etc), additional dependencies are required - please see here for details.

Add the following lines to build.sbt - the lib is hosted in Maven Central and JCenter:

resolvers += "JCenter" at "https://jcenter.bintray.com"
libraryDependencies += "io.fintrospect" %% "fintrospect-core" % "14.13.0"

See the code

See the examples or cookbook in this repo, or clone the full example application repo.

Learn it

See the full user guide here, or read on for the tldr; example. :)

Server-side contracts

Adding Fintrospect routes to a Finagle HTTP server is simple. For this example, we'll imagine a Library application (see the example above for the full code) which will be rendering Swagger v2 documentation.

Define the endpoint

This example is quite contrived (and almost all the code is optional) but shows the kind of thing that can be done. Note the use of the example response object, which will be broken down to provide the JSON model for the Swagger documentation.

// Response building methods and implicit conversion from ResponseBuilder -> Future[Response] pulled in here
import io.fintrospect.formats.Argo.ResponseBuilder._
import io.fintrospect.formats.Argo.JsonFormat.array

class BookSearch(books: Books) {
  private val maxPages = Query.optional.int("maxPages", "max number of pages in book")
  private val minPages = FormField.optional.int("minPages", "min number of pages in book")
  private val titleTerm = FormField.required.string("term", "the part of the title to look for")
  private val form = Body.form(minPages, titleTerm)

  private def search() = Service.mk[Request, Response] { 
    request => {
      val requestForm = form <-- request
      Ok(array(
        books.search(
            (minPages <-- requestForm).getOrElse(MIN_VALUE), 
            (maxPages <-- request).getOrElse(MAX_VALUE),
            titleTerm <-- requestForm
        ).map(_.toJson)))
    }
  }

  val route = RouteSpec("search for books")
    .taking(maxPages)
    .body(form)
    .returning(Status.Ok -> "we found your book", array(Book("a book", "authorName", 99).toJson))
    .returning(Status.BadRequest -> "invalid request")
    .producing(ContentTypes.APPLICATION_JSON)
    .at(Method.Post) / "search" bindTo search
}

Define a module to live at http://{host}:8080/library

This module will have a single endpoint search:

val apiInfo = ApiInfo("Library Example", "1.0", Option("Simple description"))
val renderer = Swagger2dot0Json(apiInfo) 
val libraryModule = RouteModule(Root / "library", renderer)
    .withRoute(new BookSearch(new BookRepo()).route)
Http.serve(":8080", new HttpFilter(Cors.UnsafePermissivePolicy).andThen(libraryModule.toService)) 

View the generated documentation

The auto-generated documentation lives at the root of the module, so point the Swagger UI at http://{host}:8080/library to see it.

Client-side contracts

Declare the fields to be sent to the client service and then bind them to a remote service. This produces a simple function, which can then be called with the bindings for each parameter.

Since we can re-use the routes between client and server, we can easily create fake implementations of remote systems without having to redefine the contract. This means that marshalling of objects and values into/out of the HTTP messages can be reused.

  val theDate = Path.localDate("date")
  val gender = FormField.optional.string("gender")
  val body = Body.form(gender)

  val sharedRouteSpec = RouteSpec()
    .body(body)
    .at(Get) / "firstSection" / theDate

  val fakeServerRoute = sharedRouteSpec bindTo (dateFromPath => Service.mk[Request, Response] {
    request: Request => {
      // insert stub server implementation in here
      println("Form sent was " + (body <-- request))
      Ok(dateFromPath.toString)
    }
  })

  Await.result(new TestHttpServer(10000, fakeServerRoute).start())

  val client = sharedRouteSpec bindToClient Http.newService("localhost:10000")

  val theCall = client(
    body --> Form(gender --> "male"), 
    theDate --> LocalDate.of(2015, 1, 1)
  )

  println(Await.result(theCall))

Upgrading?

See the changelog.

Contributing

There are many ways in which you can contribute to the development of the library:

  • Give us a ⭐️ on Github - you know you want to ;)
  • Questions can be directed towards the Gitter channel, or on Twitter @fintrospectdev
  • For issues, please describe giving as much detail as you can - including version and steps to recreate

See the contributor guide for details.