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.router
— Method.Joseki.router(endpoints; middleware=default_middleware, error_fn=error_responder)
Construct a HTTP.Servers.Server
from an array of Tuples
of the form (endpointfunction, httpmethod, endpoint_route).
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.
Joseki.content_type!
— Method.Sets Content-Type
for JSON responses.
Joseki.hit_logger!
— Method.Log a line whenever you get a request. HTTP.jl already does this.
Joseki.body_logger!
— Method.Log the request body. Use with care, as the request body could be very large.
Responders
Joseki.json_responder
— Method.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>
}
Joseki.error_responder
— Method.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,
"message": "You need to pass variables named x and y in the query string"
}
Joseki.unhandled_error_responder
— Method.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.
Utilities
Joseki.body_as_dict
— Method.body_as_dict(req::HTTP.Request)
Endpoints that expect a POST
request with a json-encoded body can use this.