Joseki.jl

Joseki.jl

Suggested opening moves for build APIs in Julia with HTTP.jl.

Contents

Introduction

Want to make an API in Julia but not sure where to start? Newer versions of HTTP.jl have everything you need to build one from scratch, but getting started can be a bit intimidating at the moment. Joseki.jl is a set of examples and tools to help you on your way. It's inspired by Mux.jl and Express.

You can see a simple example in the main Readme.md file.

Basics

Joseki.serverMethod.
Joseki.server(endpoints; middleware=default_middleware error_fn=error_responder)

Construct a HTTP.Servers.Server from an array of Tuples of the form (endpoint_function, http_method, endpoint_route).

source
Joseki.stackMethod.
stack(fns::Array{Function, 1}, endpoint::Function; error_fn=(req, err)->rethrow(err))

Create a HTTP.Handlers.HandlerFunction from a set of middlware functions (of the form HTTP.Request => HTTP.Request) and an endpoint (of the form HTTP.Request => HTTP.Response). If error_fn is not provided then any requests that cause an unhandled error respond with the default HTTP.jl rendering of that error (a plain text string).

source

Middleware

Joseki.add_cors!Method.

This sets Access-Control-Allow-Origin to the requester's origin. In production you would want to check the origin against a whitelist and throw an error otherwise.

source

Sets Content-Type for JSON responses.

source
Joseki.hit_logger!Method.

Log a line whenever you get a request. HTTP.jl already does this.

source

Log the request body.

source

Responders

json_responder(req::HTTP.Request, o)

Forms a response in a standard format. o can be a Number, String, Dict, or an Array of one of the other types. The response will look like:

{
    "error": false,
    "result": <JSON serialization of o>
}
source
error_responder(req::HTTP.Request, e::String)
error_responder(req::HTTP.Request, e::Exception)
error_responder(e::Exception)

Returns a response representing an error in a standard format. Errors captured within endpoints are considered to be user errors and return 200 responses. Errors not explicitly captured by a try ... catch block return 500 responses. The response will look like:

{
    "error": true,
    "result": "You need to pass variables named x and y in the query string"
}
source
unhandled_error_responder(req::HTTP.Request,e::Exception)

The default error handler, not intended for use by users. It includes a gentle reminder that errors should typically be caught elsewhere.

source

Utilities

body_as_dict(req::HTTP.Request)

Endpoints that expect a POST request with a json-encoded body can use this.

source

Index