How-to guides

Configure the whole API at once

Give the API's endpoints a supertype, and declare what every request needs on it:

abstract type ExampleEndpoint <: AbstractEndpoint end

@globalconfig RequestConfig("https://api.example.com/v1") auth=(QueryAuth("api_key"), :optional) supertype=ExampleEndpoint

RestClient.headers(::RequestConfig, ::Type{ExampleEndpoint}) =
    ["Accept" => "application/vnd.example+json",
     "User-Agent" => "ExampleClient/0.1 (example@example.com)"]
RestClient.parameters(::RequestConfig, ::Type{ExampleEndpoint}) = ("format" => "json",)
  • Define them for Type{ExampleEndpoint}, not Type{<:ExampleEndpoint}, or they are sent once for every type below it too.
  • An endpoint that gives a header or parameter of the same name replaces the API-wide one, and a given Accept or User-Agent replaces RestClient's own.
  • With an :optional auth policy the key is sent only when a config has one, so callers without a key need nothing more.

See headers, parameters, @globalconfig and AuthScheme.

Raise the API's own errors

Declare the type the API's error bodies read as, and every failure raises a ResponseError carrying it as its detail:

@jsondef struct ExampleError <: Exception
    code::Int
    message::String
end

Base.showerror(io::IO, err::ExampleError) =
    print(io, "Example API error ", err.code, ": ", err.message)

RestClient.errortype(::ExampleEndpoint) = ExampleError

A caller then catches them by type:

try
    lookup("missing-id")
catch err
    err isa ResponseError{ExampleError} || rethrow()
    @warn "Lookup refused" err.detail.code
end

Errors reported inside a 200 are caught too: a body that doesn't read as the result is tried as the error type, so give that type a required field successful bodies lack. An error body that also reads as a valid result (an empty list with an error key beside it, say) needs a check in postprocess, which throws the error type to raise it as a ResponseError:

RestClient.postprocess(::Request{<:Any, SummaryEndpoint}, summary::Summary) =
    if isnothing(summary.error) summary else throw(ExampleError(0, summary.error)) end
  • For errors in several shapes, declare an abstract error type with a subtype chosen per body (as by JSON.jl's @choosetype), and give it a format of its own with RestClient.dataformat(::Type{AnyExampleError}) = JSONFormat().
  • One endpoint can have its own error type, as in @endpoint lookup(id) -> "items/{id}" -> Item | LookupError.

See errortype.

Page through results

Declare the page as a ListResponse, and a call returns a List of its items. nextpage fetches the page after it, and eachpage walks them all, lazily:

for page in Iterators.take(eachpage(search("julia")), 3)
    foreach(println, page)
end

An API that pages by Link: <…>; rel"next"= headers needs no nextpage method. For any other scheme, say where the next page is with a nextpage(endpoint, data) method. By page number, until the response says there are no more:

RestClient.nextpage(search::SearchEndpoint, results::SearchResults) =
    if results.has_more SearchEndpoint(search; page = search.page + 1) end

By offset, stepping by the page size requested (a page can come back short) until the total is reached:

RestClient.nextpage(listing::ListingEndpoint, page::ListingPage) =
    if listing.offset + listing.limit < page.total
        ListingEndpoint(listing; offset = listing.offset + listing.limit)
    end

A cursor works the same way, with ListingEndpoint(listing; cursor = page.next_cursor), and for a next-page URL in the response, return the URL itself.

Each @endpoint struct has a copy constructor, Endpoint(old; field = new), which these use. To show "page 2 of 7", give thispagenumber for an endpoint that starts partway through, and pagecount for the total. A response that is a bare JSON array is read by a @jsondef Vector struct, as the ListResponse reference shows.

Respect a rate limit

Give the published limit as the config's RateLimit, in requests a second, and requests are paced to it:

RequestConfig("https://api.example.com"; ratelimit = RateLimit(100 / 60))  # 100 a minute
RequestConfig("https://api.example.com"; ratelimit = RateLimit(inflight = 1))  # one at a time
  • A pause the server asks for, with Retry-After or an exhausted X-RateLimit-Remaining, is waited out.
  • For a rule the headers don't carry, such as "wait a full minute after any 429", return the wait from nextallowed, as in RestClient.nextallowed(::ExampleEndpoint, r) = if r.status == 429 60 end.
  • If the API counts some endpoints separately (GitHub's searches, Slack's method tiers), give them a ratebucket, so using up one limit doesn't hold back the rest: RestClient.ratebucket(::SearchEndpoint) = :search.
  • To show a caller how many requests they have left, read quota.
  • To be told rather than kept waiting, give the config a timeout: a request that would wait longer raises a RateLimitError instead.

Use a second host or key

A config holds one base URL and one key. For another host, or another key, derive a config from the API's, which @globalconfig without arguments gives, keeping its other settings:

const GEOCODING = RequestConfig(@globalconfig; baseurl = "https://geocoding.example.com/v1")

Pass a derived config as the first argument of an endpoint function. Outside the module, RestClient.globalconfig(Val(Example)) gives its config, as in search(RequestConfig(RestClient.globalconfig(Val(Example)); key = "…"), "julia"). For an endpoint that always lives on the second host, leave out the function form and write the function yourself:

@endpoint struct GeocodeEndpoint
    "search?{name}&{count}" -> Places
    name::String
    count::Int = 10
end

geocode(name::String; count::Int = 10) =
    perform(Request{:get}(GEOCODING, GeocodeEndpoint(name, count)))

Requests through configs with the same host and key are paced together, as the server counts them; a different key is paced apart.

Add a data format

Define a format type, its media type, and how to read it, then assign it to the types that come in it:

struct FASTAFormat <: RestClient.AbstractFormat end

RestClient.mimetype(::FASTAFormat, ::Type) = "text/x-fasta"

struct FastaRecord
    header::String
    sequence::String
end

RestClient.dataformat(::Type{FastaRecord}) = FASTAFormat()

function RestClient.interpretresponse(data::AbstractVector{UInt8}, ::FASTAFormat,
                                      ::Type{Vector{FastaRecord}})
    map(split(String(copy(data)), '>'; keepempty = false)) do entry
        header, lines... = split(entry, '\n')
        FastaRecord(header, join(lines))
    end
end

An endpoint -> Vector{FastaRecord} then asks for text/x-fasta and reads the reply with this method, unless an Accept header is given: an API-wide one, as in the first section, would need replacing on that endpoint. Read from a copy of data, as String(data) empties it. To send the format too, define writepayload for it.

Test offline

You can check your types against a saved response with interpretresponse, which is how RestClient reads every body:

RestClient.interpretresponse(read("sample.json"), JSONFormat(), SearchResults)

To test a postprocess or nextallowed method, build the response it would see:

RestClient.Response("https://api.example.com/search", 429, "HTTP/1.1 429",
                    RestClient.Headers(["Retry-After" => "30"]))

Inspect requests and responses

Set JULIA_DEBUG=RestClient to log every request and response, with their headers. A request or response with a body has it saved to a file in a temporary folder, named in the log, which is deleted when Julia exits. To see it from within a script, wrap the calls in withenv("JULIA_DEBUG" => "RestClient") do … end.

A response's Response source says whether it came from the network or the cache.