API
Macros
RestClient.@globalconfig — Macro
@globalconfig config [auth=scheme | auth=(scheme, policy)] [format=fmt] [supertype=T]
@globalconfigDefine globalconfig for the current module as config, and optionally module-wide authentication, format and supertype defaults for its endpoints. Without arguments, give the current module's config, such as to derive another from it: RequestConfig(@globalconfig; key).
This avoids having to write the slightly awkward RestClient.globalconfig(::Val{@__MODULE__}) = config by hand. Similarly, the optional auth clause defines a RestClient.globalauthdefault(::Val{@__MODULE__}) method. The auth argument may take one of two forms:
auth = scheme: theAuthSchemeendpoints in this module use (e.g.BearerAuth()); the request'skeyis applied to it. With no policy given, the policy is:off— declare the scheme, but send it only where an endpoint opts in.auth = (scheme, policy): also set theauthpolicy, one of::off— never send auth (the scheme is declared but unused here);:optional— send thekeyif one is set, but do not require it;:required— send thekey, and reject a request that has none before sending.
The format clause sets the AbstractFormat of values that have none of their own, such as a Vector{String} or Dict{String, Any} result, or a String to decode as JSON, in place of RawFormat. Bytes (Vector{UInt8}, IO) stay raw. It may be a format, such as JSONFormat(), or the shorthand :json or :xml. A dataformat method for an endpoint and type still takes precedence.
The supertype clause gives every @endpoint in the module that declares no supertype of its own this one, an abstract subtype of AbstractEndpoint for behaviour the API's endpoints share (see AbstractEndpoint for which methods can be shared). Since a struct's supertype is fixed when it is defined, @globalconfig must come before the endpoints it applies to.
See also: globalconfig, RequestConfig, authscheme.
Examples
@globalconfig RequestConfig("https://api.example.com")
# Send a Bearer token on every endpoint when a key is set:
@globalconfig RequestConfig("https://api.example.com") auth=(BearerAuth(), :optional)
# Require a key on every endpoint (mark public ones `:noauth`):
@globalconfig RequestConfig("https://api.example.com") auth=(BearerAuth(), :required)
# Read and send plain values (e.g. a `Vector{String}`) as JSON:
@globalconfig RequestConfig("https://api.example.com") format=:jsonRestClient.@endpoint — Macro
@endpoint struct ... end
@endpoint [func(...)] -> [struct ... end] -> [payload] -> url -> [resulttype]Generate an endpoint implementation from a concise shorthand form.
This macro can be applied to either an endpoint struct definition or a chain of arrow forms joined by ->. These arrow forms represent the flow of information:
- The creation of a request, from a function call (optional)
- The
structused to represent the request data (optional, autogenerated from the function call) - Any payload provided with the request (if applicable)
- The page URL the request is directed to (relative to the base URL)
- The type that the response is expected to correspond to
For a basic API, this can be as simple as:
@endpoint israining(city::String) -> "checkrain/{city}" -> BoolUsing this macro is equivalent to implementing a plain struct, along with these endpoint methods:
urlpathparameters(if needed)payload(optionally)responsetype
urlpath, parameters and payload are defined in their two-argument form, taking the request's RequestConfig first, so they take precedence over any method on a supertype. Parameters every endpoint of an API needs are instead defined for the API's type, and are added to those generated (see parameters), as are those of a one-argument parameters(endpoint) method, for pairs a template can't spell, such as a set only known when sent.
In our @endpoint israining() ... example, in addition to defining the israining function and an (implicit) IsrainingEndpoint struct, the macro will generate the implementations urlpath(rain::IsrainingEndpoint) = "checkrain/$(rain.city)" and responsetype(::IsrainingEndpoint) = Bool.
In addition to applying @endpoint to a sequence of arrow forms you can also apply it to a struct that starts with a special line of non-struct arrows.
For instance, our israining() example could be alternatively written as:
@endpoint struct IsrainingEndpoint
israining(city) -> "checkrain/{city}" -> Bool
city::String
endThis generates the exact same code as the initial example form.
For more information on how each component of the shorthand form is interpreted, as well as more complex examples, see the extended help section.
See also: urlpath, parameters, payload, responsetype, Request, globalconfig, @globalconfig.
Extended help
Function forms
Should you choose to include a function call as the first arrow form, a function definition with a matching signature will be generated. This requires globalconfig(::Val{@__MODULE__}) to be defined, as is done by @globalconfig.
Without a struct form, the arguments of the function will be used to generate a struct named after the function, with each _-separated word capitalised and joined, and Endpoint appended (getUserInfo gives GetUserInfoEndpoint, and list_repos gives ListReposEndpoint), and populate its fields. A name already taken by something else, such as get_user_info's struct, is refused: give one of them a struct form to name it.
With a struct form, all arguments that match a field name will inherit the field's type and default value, though a positional argument followed by a required one stays required. All the fields of the struct not present in the signature will be added as keyword arguments, with Union{..., Nothing} typed fields defaulting to nothing. This makes function forms an easy way to prescribe positional, mandatory arguments with the flexibility to fully specify the endpoint with keyword arguments.
Two endpoints may give functions of the same name with different arguments, which become methods of one function, as fetch(ids::Vector{String}) and fetch(history::SearchHistory) might.
A docstring on an @endpoint with a function form documents the function, and the struct is given a docstring that points to it. Without a function form, the docstring documents the struct.
"""
dothing(input) -> Output
Do the thing to `input`.
"""
@endpoint dothing(input::Foo) -> "thing/{input}" -> OutputAuthentication markers
An @endpoint can start with a marker setting its authpolicy in place of the API's default: :auth requires the request's key, :authoption sends it if one is set, and :noauth never sends it.
@endpoint :auth whoami() -> "me" -> UserStruct forms
The endpoint struct can be given explicitly, or generated from the function call. For instance, the function call api(target::String; count::Int=1) will generate this struct form:
@kwdef struct ApiEndpoint
target::String
count::Int = 1
endWhen autogenerated, or not specified, the endpoint's supertype is that set by @globalconfig's supertype option, or else AbstractEndpoint. What a request returns follows from its result type alone (see AbstractEndpoint), so any supertype, such as one shared across an API, works for any result.
If @endpoint is directly applied to a struct, the first line of the struct is removed and parsed as a series of arrow forms. That line is always taken as the endpoint's, so a string there is its URL; a docstring for the first field goes after it.
@endpoint struct ApiEndpoint
api(target; count) -> ...
target::String
count::Int = 1
endThis makes no difference to the generated code; the explicit struct form can be clearer for more complex endpoints.
An endpoint struct can also be copied with some of its fields changed, as ApiEndpoint(endpoint; count = 2), such as to give the next page in nextpage.
Payload forms
HTTP methods like :post, :put, and :patch include a content payload (also referred to as the request body). The payload can be specified with a payload form that names a field of the endpoint struct, names a global variable, or is an expression evaluated to generate the payload value (with the current endpoint available through the anaphoric variable self). Fields can be named directly within the expression too, as in -> Upload(content) ->; a field sharing its name with a global variable must be written as self.field.
Unless otherwise specified, an endpoint that includes a payload is assumed to be a :post request (:get without).
@endpoint upload(content::String) -> content -> "create" -> StatusThis is equivalent to the explicit HTTP method form:
@endpoint upload(content::String) -> content -> :post("create") -> StatusIn this example content is a String, and so a :post request is made to "$BASEURL/create" with content as the payload/body. More complex types are encoded by writepayload, according to their dataformat.
URL forms
The endpoint URL is represented by a string, relative to the base URL of the API (a leading / is stripped). Such paths usually consist of a path component, and optionally a query component.
"some/path/for/my/api?query=param&other=value"Within this endpoint URL, you can include references to fields of the struct (or global variables) by surrounding them with curly braces.
"page/{somefield}?param={another}&{globalvar}=7"Parameters with a value of nothing are omitted from the query string, a collection (a Vector, Tuple, or Set) is sent as one parameter per element (?tag=a&tag=b, or nothing for an empty one), and other values are converted with string. A component without a value (?verbose) is sent as written. In the path, nothing is an error rather than omitted.
string sends a Bool as true or false, which some APIs read as set whatever its value; for those, send {Int(flag)}. An API that wants a list as one comma-joined parameter (?tags=a,b) can be given one with {join(tags, ',')}. An expression is given its fields as they are, so one for an optional field handles nothing itself, as in {if !isnothing(tags) join(tags, ',') end}.
For convenience, a parameter by the same name as the field can be referred to by the field name alone (e.g. ?{var} instead of ?var={var}), and {pairs...} splices in a collection of name => value pairs, such as a Dict, for a set of parameters only known when sent (?action=query&{continuation...}), or none for nothing. Their values are sent as other parameters' are.
A template too long for one line can be split into string literals joined by *, in parentheses as -> binds more tightly, and is read as one template:
@endpoint issues(owner, repo; state, labels, page) ->
("repos/{owner}/{repo}/issues" *
"?{state}&{labels}&{page}") -> Vector{Issue}In more complex cases, arbitrary Julia code can be included in the curly braces. This code will be evaluated with the endpoint value bound to the anaphoric variable self as well as config for the request configuration. Fields can be named directly in the code too, as in payload forms.
"page/{if self.new \"new\" else \"fetch\" end}/{id}"If that's not enough, you can also use an arbitrary expression in place of the endpoint string:
if self.create "pages/create/" else "pages/fetch/id/" * self.id endWhen using expression instead of a string though, curly braces are not interpreted as field references.
Specifying the HTTP method
By default, it is guessed whether the API expects a :get or :post request based on the presence or absence of an input form. This can be explicitly specified by wrapping the URL form in an HTTP method symbol, for example:
:head("existence/{entity}")A :query endpoint sends its payload as a QUERY request: like a :post, but safe and idempotent, so its responses are cached like a :get's (keyed on the payload too). The payload is required, since it is the query.
@endpoint search(filter::Filter) -> filter -> :query("items") -> Vector{Item}Response type forms
It is sensible to parse the raw response into a more informative Julia representation. The response type specifies what type the response can be parsed to, which is performed by interpretresponse according to dataformat.
Often the result type will name a struct defined with [@jsondef].
The result type may be omitted when the response body is of no interest, which is equivalent to giving Nothing: the body is discarded, the response is never cached, and the endpoint returns nothing.
@endpoint announce(msg::String) -> msg -> :post("events")When the URL is an expression rather than a string (or :method(url) form), the result type cannot be told apart from it, so must be given explicitly.
An error type may follow the result type (or the URL, when there is none) after a |. It is the errortype this endpoint's error responses are read as, overriding any its API's supertype declares.
@endpoint lookup(id::String) -> "lookup/id/{id}" -> Gene | EnsemblErrorThe parsed result can be reinterpreted into another form with postprocess. By default, ListResponse-type responses are restructured into a List to facilitate paging.
Examples
@endpoint struct ShuffleEndpoint
"deck/{deck}/shuffle?remaining={ifelse(self.remaining, '1', '0')}" -> Deck
deck::String
remaining::Bool
endThis is equivalent to defining the struct by itself, and then separately defining the three basic endpoint methods.
struct ShuffleEndpoint
deck::String
remaining::Bool
end
RestClient.urlpath(shuf::ShuffleEndpoint) =
"deck/$(shuf.deck)/shuffle"
RestClient.parameters(shuf::ShuffleEndpoint) =
["remaining" => ifelse(shuf.remaining, "1", "0")]
RestClient.responsetype(shuf::ShuffleEndpoint) = DeckRestClient.@jsondef — Macro
@jsondef [:noshow] [kind] struct ... endDefine a struct that can be read from and written as JSON.
This macro conveniently combines the following pieces:
@kwdefto define keyword constructors for the struct.- Custom
Base.showmethod to show the struct with keyword arguments, omitting default values (suppress with the:noshowoption). - Registration of the JSON field-name mapping with JSON.jl.
RestClient.dataformatto declare that this struct is JSON-formatted.
Note the name."json_field" syntax demonstrated in the examples, that allows for declaration of the JSON object key that should be mapped to the field. The key is one name, not a path into nested objects; model those with a nested type. Keys of the JSON object that no field names are ignored. A field typed Union{…, Nothing} defaults to nothing. A field that is nothing is left out of the JSON written, as most APIs read a missing key as "not given"; to send an explicit null, type the field Union{Nothing, JSON.Null} and set it to JSON.Null().
A field may take StructUtils' field tags after its type, for a value the JSON gives in another form: lift makes the field from the JSON value, and dateformat reads a date or time in that format. A DateTime already reads ISO 8601, with or without a Z or an offset.
The struct may have a supertype, such as <: ListResponse{Item} or <: Exception, and type parameters, as in Page{T} <: ListResponse{T}.
@jsondef struct Search
count::Int &(lift = s -> parse(Int, s),) # sent as "1053"
created."creation_date"::DateTime &(lift = unix2datetime,)
day::Date &(dateformat = "yyyymmdd",) = Date(2000)
endThe optional kind argument selects the JSON representation, one of Struct (the default), Dict, Array, Vector, Nothing, and String. For String, the user must define Base.string and a T(::AbstractString) constructor. A number or boolean representation needs user-defined StructUtils.lift / StructUtils.lower methods instead.
For an open-ended JSON object or array, a struct with a single field of kind Dict or Array/Vector reads the whole object or array into that field, whether it is the response itself or nested within another struct. A container kind with more fields is read and written as a struct of its fields, like Struct.
@jsondef Dict struct Translations
entries::Dict{String, String} # {"en": "Hello", "fr": "Bonjour"} → Translations(...)
endThis macro is implemented in a package extension, and so requires JSON to be loaded before it can be used.
Examples
@jsondef struct DocumentStatus
exists::Bool # Required, goes by 'exists' in JSON too
status."document_status"::Union{String, Nothing} = nothing
url."document_url"::Union{String, Nothing} = nothing
age::Int = 0 # Known as 'age' in JSON too, defaults to 0
endRestClient.@xmldef — Macro
@xmldef struct ... endDefine a struct that can be used with XML.
This macro conveniently combines the following pieces:
- XML deserialization
@kwdefto define keyword constructors for the struct.- A
Base.showmethod showing the struct with keyword arguments, omitting default values, as@jsondefdoes. RestClient.dataformatto declare that this struct is XML-formatted.
Note the name."xpath" syntax demonstrated in the examples, that allows for declaration of the (simple) XPath that should be used to extract the field. A field without one reads the child element named after it, so title::String reads <title>. Paths start from the document's root element, whose own name isn't checked, so title reads <feed><title>, and tags are matched as written, namespace prefix and all: arxiv:comment matches only that prefix. The subset of supported XPath components are:
nodetagto extract all immediate children with a given tag name.to extract the node itself, such as its whole text, or a type read from the same elementrelative/node/paths*to extract all childrentext()to extract a node's own text, without that of elements within it@attrto extract the value of an attributenodetag[i]to extract thei-th child of typenodetagnodetag[last()]to extract the last child of typenodetag
A text or number field read from an element takes all the text within it, so <title><i>E. coli</i> Nissle</title> gives "E. coli Nissle" where title/text() gives " Nissle".
A field whose XPath matches nothing takes its default value. Unlike plain @kwdef, a default can't refer to other fields. A Vector field takes every match through every step of its path, so a/@b gives the b of each a. Other fields need each step before the last to match one element; at the last, a Union{…, Nothing} field takes the first of several, and any other field requires exactly one.
A Date or DateTime field reads ISO 8601 text, as in JSON, with any Z or offset taken to UTC. A field may take the same tags as in @jsondef: lift makes the field from its text (each match's, for a Vector), and dateformat reads a date or time in that format, as in published::DateTime &(dateformat = "yyyy-mm-dd HH:MM",).
This macro is implemented in a package extension, and so requires XML to be loaded before it can be used.
Examples
@xmldef struct DocumentStatus
exists."status/@exists"::Bool
status."status"::String
url."status/@url"::Union{String, Nothing} = nothing
age."status/@age"::Int
endRestClient.@formdef — Macro
@formdef struct ... endDefine a struct that serialises as FormFormat. Supports the name."form_key"::Type syntax for remapping a field's form name. A field typed Union{…, Nothing} defaults to nothing, and is left out of the form when nothing. A collection (a Vector, Tuple, or Set) is sent as one field per element, as in tags=a&tags=b.
Example
@formdef struct Login
username::String
password::String
remember_me."remember-me"::Bool = false
endRestClient.@multipartdef — Macro
@multipartdef struct ... endDefine a struct that serialises as MultipartFormat. Each field is encoded with its type's own dataformat: @jsondef fields become JSON parts, Vector{UInt8} / IO fields become octet-stream file parts, and others become text parts. A MultipartFile field sets its file's name and Content-Type. A collection without a format of its own, such as a Vector{String} or a Vector{Vector{UInt8}}, is sent as one part per element under the field's name. As with @formdef, a field typed Union{…, Nothing} defaults to nothing, and is left out when nothing.
Example
@multipartdef struct Upload
file::Vector{UInt8}
metadata::Metadata # `@jsondef struct Metadata ... end`
note::Union{String, Nothing}
endRequest types
RestClient.Request — Type
Request{kind, E<:AbstractEndpoint}A request to an API endpoint, with a specific configuration.
This is the complete set of information required to make a kind HTTP request to an endpoint E. This consists of the request configuration and target endpoint itself. The kind and endpoint::E are put as type parameters so that they may participate in method dispatch.
See also: AbstractEndpoint, RequestConfig, perform.
Examples
julia> Request{:get}(RequestConfig(...), MyEndpoint(...))
Request{:get, MyEndpoint}(RequestConfig(...),MyEndpoint(...))Data flow
╭─╴config╶────────────────────────────╮
│ ╎ │
│ ╎ ╭─▶ responsetype ╾─────┼────────────────┬──▶ dataformat ╾───╮
Request╶─┤ ╰╶╶╶╶╶╶╶╶│ │ ╰─────────╮ │
│ ├─▶ urlpath ╾────╮ │ ╓┄┄*debug*┄┄╖ │ ╭──────╯
│ │ ├──▶ url ╾─┬─━─▶ request ┊ ╭─▶ interpret ╾──▶ data
├─╴endpoint╶───┼─▶ parameters ╾─╯ │ ┊ ┠────━─┤ │
│ │ ├─━──▶ cache ┊ │ ╭─────╯
│ ├─▶ headers ╾───────────────┤ ┊ ┊ ╰─────────╮ │
│ │ │ ╙┄┄┄┄┄┄┄┄┄┄┄╜ postprocess ╾──▶ result
│ *╰─▶ payload ─▶ writepayload╶╯ │
│ ╰─▶ dataformat ╾╯ │
╰─────────┬────────────────────────────────────────────────────────────╯
╰────▶ validate (before initiating the request)
* Only with a payload ╶╶ Optional first argumentRestClient.RequestConfig — Type
RequestConfig(baseurl::String; key, ratelimit, timeout, cache)
RequestConfig(config::RequestConfig; baseurl, key, ratelimit, timeout, cache)The general configuration for a request to the API, not tied to any specific endpoint.
At a minimum, this holds the base URL of the API. Requests through every config with the same host and key are paced together, as the server counts them together (or by ratebucket, where it counts some apart).
Other fields are optional, but may be useful for changing the way requests are performed or handling authentication. The following additional fields can be provided as keyword arguments:
key::Union{Nothing, String}: The secret used to authenticate requests. How it is presented on the wire is declared by endpoints. It is shown as*****in the REPL and in errors and debug output, butreprandstringgive it in full.ratelimit::RateLimit: How fast requests may be sent, seeRateLimit. Defaults to no limit, though a response's rate-limit headers are always kept to.timeout::Float64: The longest a request may take, in seconds, or for aStream, the longest it may go without receiving data. Defaults toInf, no limit, so a stream waits as long as it takes. Even so, a request is abandoned if its response stops for 20 seconds partway, or takes 120 seconds to begin (ortimeout, if longer). Either limit raises aTransportError.cache::Bool: Whether to cache the response, using lifetime information from standard HTTP response headers. Defaults totrue. Responses are kept on disk in the user's cache directory (on Linux,~/.cache/julia/restclient/), so they last between sessions; entries past their lifetime are cleared as Julia exits, and deleting that folder clears the whole cache.
The second form derives a config from config, with any of its fields overridden, such as another key or host.
See also: @globalconfig, Request.
Examples
julia> RequestConfig("https://api.example.com", timeout = 5, cache = false)
RequestConfig("https://api.example.com"; timeout = 5.0, cache = false)
julia> config = RequestConfig("https://api.example.com", key = ENV["API_SECRET_KEY"])
RequestConfig("https://api.example.com"; key = "*****", cache = true)
julia> RequestConfig(config, key = nothing, timeout = 300)
RequestConfig("https://api.example.com"; timeout = 300.0, cache = true)RestClient.RateLimit — Type
RateLimit(rate::Real = Inf; burst::Integer = 1, inflight::Integer = typemax(Int))How fast requests through a RequestConfig, and any other for the same host and key, may be sent (for each ratebucket): on average at most rate a second, up to burst of them at once, with no more than inflight awaiting a response at a time (a Stream until it's closed or ends). A request that would exceed the limit waits until it may be sent.
Give a limit published over a window, such as "100 a minute", as its rate, RateLimit(100/60). A burst of the window's whole count would let up to twice that through in some windows.
See also: nextallowed, for limits a response reports.
Examples
RequestConfig("https://export.arxiv.org/api"; ratelimit = RateLimit(1/3))
RequestConfig("https://lichess.org/api"; ratelimit = RateLimit(inflight = 1))RestClient.AbstractEndpoint — Type
AbstractEndpointAbstract supertype for API endpoints.
What a request to an endpoint returns follows from its responsetype: a ListResponse is wrapped in a List, a SingleResponse gives its contents, and a Stream is read incrementally.
To share behaviour across an API's endpoints (auth, validation, logging), define an abstract subtype for the API and give it the shared methods. Headers and parameters for the whole API are defined for the type, and add to each endpoint's own (see headers). Other methods, such as validate, apply unless an endpoint has its own, and those @endpoint generates (urlpath, parameters, payload) always are.
Interface
urlpath([config::RequestConfig], endpoint::AbstractEndpoint) -> String
headers([config::RequestConfig], endpoint::AbstractEndpoint) -> Vector{Pair{String, String}}
parameters([config::RequestConfig], endpoint::AbstractEndpoint) -> Vector{Pair{String, String}}
responsetype(endpoint::AbstractEndpoint) -> Type
errortype(endpoint::AbstractEndpoint) -> Type
validate([config::RequestConfig], endpoint::AbstractEndpoint) -> Union{Nothing, Bool, AbstractString, AbstractVector{<:AbstractString}}
postprocess([response], request::Request, data) -> AnyAll of these functions but urlpath have default implementations.
See also: Request, dataformat, interpretresponse.
Response types
RestClient.SingleResponse — Type
SingleResponse{T}Abstract supertype for responses that wrap a single T item, such as an envelope like {"data": {...}}. A request returns the item itself.
Interface
Subtypes of SingleResponse may need to define:
contents(single::SingleResponse{T}) -> TThe generic implementation takes the response's one field of type T.
RestClient.ListResponse — Type
ListResponse{T}Abstract supertype for responses that contain a list of T items, such as a page of results with a total count. A request returns a List of the items, which keeps the response as its data.
Interface
Subtypes of ListResponse may need to define:
contents(list::ListResponse{T}) -> Vector{T}The generic implementation takes the response's field of type Vector{T}.
A response that is a bare JSON array is read by a @jsondef Vector struct with that one field. Paged by Link headers, as many such APIs are, it needs no nextpage method:
@jsondef Vector struct IssuePage <: ListResponse{Issue}
issues::Vector{Issue}
endRestClient.List — Type
List{T, E<:AbstractEndpoint, R<:Request, D}A page of T items, from an R request to an E endpoint whose response was read as a D (a ListResponse).
A List is a read-only AbstractVector of its items, so it indexes, slices and compares as they do. Its fields are request, items, data (the response's body as read, such as for a total count), response (its status and headers), and page, its number among the pages nextpage has fetched. With Tables.jl loaded, a List of structs is a table, one row per item.
See also: ListResponse, eachpage.
RestClient.Response — Type
ResponseA response from an API: as given to hooks such as postprocess and nextallowed, and kept by a List, Stream or ResponseError.
url::String: where the response came from, after any redirects.status::Int: its status code.message::String: its status line, such as"HTTP/1.1 200 OK".headers::Headers: itsHeaders.source::Symbol: where it was read from::network;:stored, the cache, without asking the server; or:revalidated, the cache, once the server said it hadn't changed (a 304). It is:networkunless given.
RestClient.Headers — Type
HeadersThe headers of a Response, looked up by name in any case.
headers[name] gives the first value of name, raising a KeyError if there is none, get(headers, name, default) gives default instead, and haskey(headers, name) says whether there is one. Iterating gives every name => value pair in order, with names in lower case, so a header sent more than once, such as Link, appears each time.
Examples
response.headers["Content-Type"]
get(response.headers, "X-RateLimit-Remaining", nothing)Errors
A failed perform raises one of these. A request that does not validate raises a MalformedRequest before anything is sent; an unsuccessful HTTP status raises a ResponseError carrying the server's response body, read as the endpoint's errortype when it declares one; and a successful response that can't be read as the endpoint's result type (malformed JSON, a missing key) raises a MalformedResponse naming the request and holding the body, unless it reads as the errortype. A request that would wait longer than its timeout to be sent, under a rate limit, raises a RateLimitError rather than being sent. A failure in transit (DNS, connection refused, TLS, exceeding the total timeout, or going silent for too long) raises a TransportError saying which, with any auth secrets hidden from its URL.
RestClient.ResponseError — Type
ResponseError{E} <: ExceptionAn exception type for requests that complete but return an unsuccessful HTTP status (outside 200:299), or a successful one that reads as the endpoint's errortype.
Unlike a bare transport failure, the server's response is available: response holds the status and headers, and body holds the raw response body, which APIs routinely use to explain why a request failed. detail holds that body read as the endpoint's errortype E, or nothing (with E as Nothing) if it declares none or the body doesn't read as it.
Examples
try
lookup("ENSG00000157764")
catch err
err isa ResponseError{EnsemblError} || rethrow()
@warn "Ensembl refused the lookup" err.response.status err.detail.message
endRestClient.RateLimitError — Type
RateLimitError <: ExceptionAn exception type for requests not sent because they would have waited longer than their config's timeout (see perform).
request is the request, and until when it could have been sent (a UTC DateTime), held back by a deadline a response set or by its config's RateLimit. An until of nothing means it waited for one of its inflight requests to finish, and none did in time.
Raise the config's timeout to wait instead, or try again later.
RestClient.MalformedRequest — Type
MalformedRequest <: ExceptionAn exception type for requests that fail validation.
RestClient.MalformedResponse — Type
MalformedResponse <: ExceptionAn exception type for successful responses that cannot be read as the expected type, such as malformed JSON or a missing required key.
request and response say where the response came from, type is what it was being read as, body holds the bytes that failed (for a Stream, the frame's payload), and error is the underlying exception.
See also: perform, interpretresponse.
RestClient.TransportError — Type
TransportError <: ExceptionAn exception type for requests that fail without a complete response.
request is the request that failed, url where it was sent (with secrets hidden), message the transport's own account of the failure, and reason what kind of failure it was:
:resolve: the host could not be found;:connect: the host could not be connected to;:tls: the secure connection failed, such as over an invalid certificate;:timeout: the request took longer than its config'stimeout;:silence: the request went too long without receiving data;:dropped: the connection closed before the response was complete;:redirects: the server redirected too many times;:other: anything else.
See also: perform, RequestConfig.
Streaming
RestClient.Stream — Type
Stream{T, F}A lazily consumed stream of elements of type T, framed by F (:SSE, the default, or :NDJSON). Like a List, it is chosen through an endpoint's output type.
Iterating it blocks until the next element has arrived and been decoded. Any task may close it, which ends iteration without an error (see the manual on cancellation), and a stream that is dropped before it is drained is reclaimed by its finalizer.
See also: isstreamend.
RestClient.SSEvent — Type
SSEvent{T}A Server-Sent Event with payload data::T (undecoded bytes off the wire, or the decoded T), the dispatching event type, and the sticky last-event-id.
Destructures as (event, data) or (event, data, id), and exposes each as a field.
RestClient.isstreamend — Function
isstreamend(endpoint::AbstractEndpoint, frame) -> BoolWhether frame ends the stream from endpoint, without reaching the consumer. The default is false, ending a stream only when the connection closes; an API that marks its end in band needs a method checking the frame.
Each frame is checked twice: before decoding, with its payload still bytes (as an SSEvent{Vector{UInt8}}), and after, as the stream's element (an SSEvent{T}, or a T). A method sees whichever its type matches, so one that reads a decoded field types the payload:
RestClient.isstreamend(::ChatEndpoint, fr::SSEvent{<:AbstractVector{UInt8}}) = fr.data == codeunits("[DONE]")
RestClient.isstreamend(::MessagesEndpoint, fr::SSEvent) = fr.event == "message_stop"
RestClient.isstreamend(changes::ChangesEndpoint, fr::SSEvent{<:Change}) = fr.data.time >= changes.untilRestClient.isstreamskip — Function
isstreamskip(endpoint::AbstractEndpoint, frame) -> BoolWhether frame is left out of the stream from endpoint, such as a keep-alive or monitoring event. Like isstreamend, it is checked before and after decoding, so a frame that wouldn't decode can be skipped by its raw form. The default is false.
RestClient.isstreamskip(::FeedEndpoint, fr::SSEvent) = fr.event == "heartbeat"
RestClient.isstreamskip(::ChangesEndpoint, fr::SSEvent{<:LogEntry}) = trueBase.isopen — Method
isopen(s::Stream) -> BoolWhether s may still receive elements: false once it has ended or been closed, though elements it already received can still be iterated.
Framing extension interface
These methods define a stream framing. The shipped :SSE and :NDJSON framings cover the common cases; a client library implementing a new framing defines these.
RestClient.StreamFormat — Type
StreamFormat{F, E<:AbstractFormat} <: AbstractFormatThe format of a streamed body: framing F (a symbol, e.g. :SSE/:NDJSON) over an element format E. readframe/framestate/mimetype dispatch on it by F.
RestClient.readframe — Function
readframe(bs::IO, state, fmt::StreamFormat) -> frame | nothingRead one complete frame from bs, with its payload still undecoded bytes, or return nothing at a clean EOF. state is framestate's value, reused across calls. Dispatched on fmt's framing. A frame type keeps its payload in a field typed by its parameter, like data::T in SSEvent{T}.
The read blocks on bs, reassembling a frame split across network reads. As bs is written concurrently, read it with calls that lock against the writer (readuntil, read, readavailable), not copyuntil or readline (which uses it).
RestClient.framestate — Function
framestate(fmt::StreamFormat)The per-stream state readframe threads across calls: nothing by default, overridden by a framing that carries state across frames.
RestClient.elementpayload — Function
elementpayload(::Type{Elt}) -> TypeThe decode target for a stream element type. Defaults to Elt; a framing whose element type wraps its payload (e.g. SSEvent{T} ⇒ T) overrides it.
Request interface
RestClient.globalconfig — Function
globalconfig(::Val{::Module}) -> RequestConfigReturn the global configuration for the given module.
This is used in @endpoint generated API functions.
See also: @globalconfig, RequestConfig.
RestClient.validate — Function
validate([config::RequestConfig], endpoint::AbstractEndpoint) ->
Union{Nothing, Bool, AbstractString, AbstractVector{<:AbstractString}}Check if the request to endpoint according to config is valid.
The return value determines whether the request proceeds and, if not, what problem to report:
nothingorString[]means the request is valid and should proceed- a string or vector of strings means the request is invalid and should be aborted, with the string(s) as the reason(s)
trueorfalsemeans valid or invalid, without a reason
This is also the appropriate place to emit warnings about non-critical potential issues with the request, using @warn or @debug.
The default implementation returns nothing (proceed).
RestClient.perform — Function
perform(req::Request{kind}) -> AnyValidate and perform the request req, and return the result.
The kind of the request is its HTTP method, one of: get, post, put, patch, delete, head, options, query. The result depends on the endpoint: the response parsed as its responsetype (read incrementally, for a Stream), passed through postprocess. A :head request's result is whether the resource exists: true on success, false on 404 or 410.
Up to 50 redirects are followed, each with the same method and body, but a 303 (See Other) with a GET without its body, as it asks. Every request identifies itself as User-Agent: RestClient.jl/<version> unless the endpoint's headers give their own.
Retries and rate limits
Requests are sent no faster than their config's RateLimit, and wait out any deadline set by a response to the same host with the same key (and ratebucket): one its headers give (a Retry-After, or an X-RateLimit-Reset with X-RateLimit-Remaining: 0), or nextallowed does. Responses served from the cache are not held back.
A 429 is retried at its deadline, or failing that after an exponential backoff (about 0.5, 1, 2 then 4 seconds, with jitter). A 403 or 503 is retried when its headers give a deadline, and any other unsuccessful response when nextallowed does. A gateway failure (502, 503 or 504) is retried after the backoff, for methods safe to repeat (not POST or PATCH), unless its body reads as the endpoint's errortype: then the API gave it, and it stands. A request is attempted at most five times.
No wait is longer than the config's timeout. A retry that would need a longer one isn't made, and the response is raised instead; a request that would be held back for longer isn't sent, and raises a RateLimitError. With the default timeout = Inf, a wait can be long (until an hourly quota resets, say), so set a timeout to bound it.
Errors
MalformedRequestif the request fails validation.ResponseErrorif the server responds with an unsuccessful status, once any retries are spent.RateLimitErrorif the request would wait longer than itstimeoutto be sent.MalformedResponseif a successful response can't be read as the endpoint'sresponsetype.ArgumentErrorifkindis not a supported HTTP method.
See also: Request.
RestClient.urlpath — Function
urlpath([config::RequestConfig], endpoint::AbstractEndpoint) -> StringReturn the name of the page for the given endpoint.
This is combined with the base URL and parameters to form the full URL for the request.
RestClient.headers — Function
headers([config::RequestConfig], endpoint::AbstractEndpoint) -> Vector{Pair{String, String}}
headers(config::RequestConfig, ::Type{T}) -> collection of `Pair{String, String}`Return headers for the given endpoint, or for every endpoint of type T.
A request sends the endpoint's own headers, then those for its type and for each of its supertypes in turn, except those named by a header before them: so headers for a whole API belong on its supertype, and an endpoint can replace one. Define these for the type itself (Type{MyAPI}, not Type{<:MyAPI}), or they are sent again for each type below it.
The default implementations return an empty list, or () for a type.
When no Content-Type (or Accept) header is provided, it is set from the payload's (or result's) mimetype; one given replaces it, as a User-Agent given replaces RestClient's own.
RestClient.parameters — Function
parameters([config::RequestConfig], endpoint::AbstractEndpoint) -> Vector{Pair{String, String}}
parameters(config::RequestConfig, ::Type{T}) -> collection of `Pair{String, String}`Return URI parameters for the given endpoint, or for every endpoint of type T.
These are combined with the endpoint URL to form the full query URL: the endpoint's own parameters, then those for its type and for each of its supertypes in turn, except those named by a parameter before them. As with headers, parameters for a whole API belong on its supertype, defined for the type itself, and an endpoint can replace one by giving it itself.
The default implementations return an empty list, or () for a type.
RestClient.payload — Function
payload([config::RequestConfig], endpoint::AbstractEndpoint) -> AnyReturn the payload for the given endpoint.
This is sent as the body of the request, whatever its method (e.g. :post, :put, :patch, or :query).
RestClient.authscheme — Function
authscheme(endpoint::AbstractEndpoint) -> AuthSchemeReturn how endpoint authenticates: the AuthScheme describing where the request's secret (config.key) is placed on the wire. The library applies it to key automatically, so a standard scheme needs no headers method.
The default is the scheme given by @globalconfig auth= in the endpoint type's module, else NoAuth. Alternatively, declare a scheme once per API on a shared endpoint supertype:
RestClient.authscheme(::MyAPIEndpoint) = BearerAuth() # Authorization: Bearer <key>
RestClient.authscheme(::OtherEndpoint) = HeaderAuth("X-API-Key")For a scheme the provided ones do not cover, define a new AuthScheme; for one that can't be expressed as a header or query parameter (request signing, OAuth flows), read config.key in a headers method directly instead.
RestClient.authpolicy — Function
authpolicy(endpoint::AbstractEndpoint) -> SymbolHow endpoint uses authentication, one of:
:off— never send auth (the default);:optional— apply theauthschemeto the request'skeyif one is set, but do not require it;:required— apply it, and reject a request whoseconfig.keyisnothingduring validation, before sending, rather than relying on the server to return 401.
The default is the policy given by @globalconfig auth= in the endpoint type's module (:off without one), looked up when a request is made. The @endpoint macro overrides it per endpoint with an :auth (required), :authoption (optional), or :noauth (off) marker.
Authentication
An endpoint declares which scheme it authenticates with via an authscheme method, and whether a key is off/optional/required via authpolicy; the secret itself is the RequestConfig's key. Both are usually set in one place with @globalconfig's auth= option.
RestClient.AuthScheme — Type
AuthSchemeSupertype for authentication schemes, which describe how an API expects its secret: in which header or query parameter, and in what form. A scheme never holds the secret itself, which is the key of a RequestConfig. Declare an endpoint's scheme with authscheme, and every request applies it to key.
The provided schemes are BearerAuth, BasicAuth, HeaderAuth, QueryAuth, and NoAuth (the default).
For any other header or query parameter scheme, define a subtype with an authheaders or authparams method. A scheme's header or parameter is hidden in debug output and errors, while a key an endpoint adds itself (in its own headers, parameters, or urlpath) is not.
struct TokenAuth <: AuthScheme end
RestClient.authheaders(::TokenAuth, key::String) = "Authorization" => "Token $key"RestClient.BearerAuth — Type
BearerAuth() <: AuthSchemeBearer-token authentication: the key is sent as Authorization: Bearer <key>. The common scheme for OAuth2 access tokens and most modern token-based APIs.
RestClient.BasicAuth — Type
BasicAuth() <: AuthSchemeHTTP Basic authentication (RFC 7617): the key (a "username:password" string) is sent as Authorization: Basic <base64>. Set key = "user:pass" on the config.
RestClient.HeaderAuth — Type
HeaderAuth(name) <: AuthSchemeThe key is sent in the named request header, e.g. HeaderAuth("X-API-Key"). For APIs that authenticate with a custom header rather than Authorization.
RestClient.QueryAuth — Type
QueryAuth(name) <: AuthSchemeThe key is sent as the named URL query parameter, e.g. QueryAuth("api_key"). For APIs that authenticate via the query string. Prefer a header scheme where the API allows it: query parameters are more likely to be logged by proxies and servers.
RestClient.NoAuth — Type
NoAuth() <: AuthSchemeNo authentication: the default authscheme. Contributes nothing, regardless of key.
RestClient.authheaders — Function
authheaders(scheme::AuthScheme, key) -> Union{Pair{String, String}, Nothing}The header scheme contributes for secret key, or nothing for a parameter-based or absent scheme, or when key is nothing. Appended to an endpoint's own headers when the endpoint's authpolicy is not :off.
RestClient.authparams — Function
authparams(scheme::AuthScheme, key) -> Union{Pair{String, String}, Nothing}The query parameter scheme contributes for secret key, or nothing for a header-based or absent scheme, or when key is nothing. Appended to an endpoint's own parameters when the endpoint's authpolicy is not :off.
Response interface
RestClient.responsetype — Function
responsetype(endpoint::AbstractEndpoint) -> TypeReturn the type of the response for the given endpoint.
Together with dataformat, this is used to parse the response.
If Vector{UInt8} (the default implementation), the response data is provided raw. If Nothing, the response body is discarded (and never cached), and the result is nothing.
RestClient.errortype — Function
errortype(endpoint::AbstractEndpoint) -> TypeReturn the type an error response to endpoint is read as, in its own dataformat, or Nothing (the default) to leave error bodies unread.
The ResponseError raised for an unsuccessful status then carries the body read as this type, as its detail. A body that doesn't read as it leaves the detail as nothing, and the error is raised all the same.
A successful response that can't be read as the endpoint's responsetype is tried as this type too, so an API that reports errors inside a 200 raises them as a ResponseError (as does a Stream element, partway through the stream). For that, the error type needs a required field that a successful body lacks, or it would read from any body. An error that also reads as a result (an empty one, say) can be thrown as this type from postprocess instead. A 502, 503 or 504 whose body reads as this type is the API's own answer, so it isn't retried as a gateway failure.
Define this for an API's endpoint supertype to read its errors from every endpoint, or give one endpoint its own with @endpoint's -> Result | Error. An abstract error type, with a subtype chosen per body (as by JSON.jl's @choosetype), is matched as declared: ResponseError{APIError}. It has no format of its own, so give it a dataformat method, or the API one with @globalconfig … format = …. Make it an Exception with a showerror method for the error to show the API's own explanation.
Examples
@jsondef struct EnsemblError
message."error"::String
end
RestClient.errortype(::EnsemblEndpoint) = EnsemblErrorRestClient.postprocess — Function
postprocess([response], request::Request, data) -> AnyPost-process the data returned by the request, by default returning it as-is.
data is the response body already read as the endpoint's responsetype: reading happens first, and a body that can't be read raises a MalformedResponse without reaching postprocess. An error status raises a ResponseError before either. To raise an error an API reports inside a successful response, declare its errortype; one that also reads as a result can be thrown here as that type, and is raised as a ResponseError like any other.
The result is then restructured: a ListResponse is wrapped in a List, and a SingleResponse gives its contents, restructured in turn (so a ListResponse inside one is still paged). So a method may check or unwrap the data, and a ListResponse it returns is still paged.
The three-argument form also sees the response, with its status and headers; by default it calls the two-argument form.
RestClient.contents — Function
contents(response::SingleResponse{T}) -> Union{T, Nothing}Return the content of the response: its T field, or failing that its Union{T, Nothing} field, which may be nothing.
contents(response::ListResponse{T}) -> Vector{T}Return the items of the response: its Vector{T} field, or failing that its Union{Vector{T}, Nothing} field, with nothing as no items.
Pagination interface
RestClient.nextpage — Function
nextpage(list::List) -> Union{List, Nothing}
nextpage([response], endpoint::AbstractEndpoint, data) -> Union{AbstractEndpoint, AbstractString, Nothing}Fetch the page after list, or return nothing if it is the last.
An endpoint gives where its next page is with the second form, from the data of the page before (its ListResponse, after postprocess), and in the three-argument form its response too: the next page's endpoint, its URL, or nothing for none. Without such a method, the page the response's Link: <…>; rel="next" header gives is fetched (RFC 8288). A URL may be absolute or start with /, and must lie under the API's baseurl.
The endpoint is that of the request for the page before, or for a page reached by URL, of the first page. Pages are numbered on from the first (see thispagenumber), and pagecount may give their total.
Examples
# A page number, until the response says there are no more
RestClient.thispagenumber(search::SearchEndpoint) = search.page
RestClient.nextpage(search::SearchEndpoint, results::SearchResults) =
if results.has_more SearchEndpoint(search; page = search.page + 1) end
# An offset, stepping by the page size until it passes the total reported
RestClient.nextpage(listing::ListingEndpoint, page::ListingPage) =
if listing.offset + listing.limit < page.total
ListingEndpoint(listing; offset = listing.offset + listing.limit)
end
# A cursor
RestClient.nextpage(works::WorksEndpoint, page::WorksPage) =
if !isnothing(page.next_cursor) WorksEndpoint(works; cursor = page.next_cursor) end
# The next page's URL, given in the response
RestClient.nextpage(::ResourcesEndpoint, page::ResourcePage) = page.nextRestClient.eachpage — Function
eachpage(list::List)Iterate over list and the pages after it (see nextpage), fetching each only when it is reached.
Examples
for page in eachpage(users()), user in page
println(user.name)
endRestClient.thispagenumber — Function
thispagenumber(list::List) -> Union{Int, Nothing}
thispagenumber(endpoint::AbstractEndpoint) -> Union{Int, Nothing}Return the number of the page list is, if it is one of several: counted on from the number the first page's endpoint gives, else 1.
An endpoint that starts partway through a listing, such as by an offset, gives its page's number with the second form; by default nothing.
RestClient.remainingpages — Function
remainingpages(list::List) -> Union{Int, Nothing}Return how many pages follow list, if pagecount gives their total.
RestClient.pagecount — Function
pagecount(list::List) -> Union{Int, Nothing}
pagecount([response], endpoint::AbstractEndpoint, data) -> Union{Int, Nothing}Return the total number of pages in the listing list is a page of, if known.
Define the second form to give it, for data read from a request to endpoint: for instance from a count of items in data, or from the three-argument form's response headers. By default nothing.
Rate limit interface
RestClient.nextallowed — Function
nextallowed(endpoint::AbstractEndpoint, response::Response) -> Union{Real, Nothing}Return when the API next allows a request after response to a request to endpoint, in seconds from now or as a Unix time (a time() value), or nothing to set no time. A time worth more than a year of seconds is taken as a Unix time.
Each response from the network is given to this, and requests to the same host with the same key (and ratebucket) wait until the later of this and the time its rate-limit headers set (Retry-After, or X-RateLimit-Reset with X-RateLimit-Remaining: 0), so a method can only lengthen the wait. An unsuccessful response with a time is retried then, and with Inf is raised without a retry. By default nothing.
See also: RateLimit, for limits known ahead of time.
Examples
# A full minute's pause after any 429
RestClient.nextallowed(::LichessEndpoint, response) = if response.status == 429 60 end
# An hourly quota used up, from a server that sends no reset time
RestClient.nextallowed(::NASAEndpoint, response) =
if get(response.headers, "X-RateLimit-Remaining", "") == "0" 3600 endRestClient.ratebucket — Function
ratebucket(endpoint::AbstractEndpoint) -> AnyReturn which of the rate limits an API keeps on one host requests to endpoint count against, or nothing (the default) for the host's one limit.
Endpoints in different buckets are paced and held back as if on different hosts: each bucket has its own RateLimit allowance and inflight count, waits out only its own pauses, and has its own quota. Any value names a bucket, such as a Symbol or the endpoint's type.
Examples
RestClient.ratebucket(::SearchEndpoint) = :search # GitHub counts searches apartRestClient.quota — Function
quota(config::RequestConfig, bucket = nothing) -> Union{Quota, Nothing}Return the rate limit the server last reported to requests through config, or any other config for the same host and key, in bucket (see ratebucket), or nothing if none has.
It is read from the response's X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset headers, as a Quota: the requests allowed and those left, and when the count renews. Responses from the cache don't count, as their headers are as old as the response.
Examples
julia> RestClient.quota(config)
RestClient.Quota: 4987 of 5000 left, renewing 2026-11-14T13:00:00 UTCRestClient.Quota — Type
QuotaThe rate limit a server reported (see quota): limit, the requests allowed; remaining, those left; and reset, when the count renews (a UTC DateTime). Each is nothing when the server didn't say.
Caching interface
RestClient.cachelifetime — Function
cachelifetime(req::Request, res::Response) -> Union{DateTime, Integer, Nothing}Determine how long a response may be served from the cache: until a (UTC) DateTime, for a number of seconds, or nothing to follow the response's HTTP caching headers. With 0, a response is out of date at once: checked with the server each time it's wanted if it has an ETag or Last-Modified, and otherwise not kept.
Specialisation
To specialise this function for a specific endpoint, define one of the following methods:
cachelifetime(req::Request{kind, <:AbstractEndpoint}, res::Response)
cachelifetime([conf::RequestConfig], endpoint::AbstractEndpoint, res::Response)Content formatting
Each type a request sends or receives has a format: its own, from @jsondef, @xmldef, @formdef or a dataformat method, or else its API's, which is raw text or bytes unless @globalconfig's format option says otherwise (e.g. format = :json for an API whose plain values, like a Vector{String}, are JSON). A single endpoint can still differ: in a JSON API, a text/plain one declares RestClient.dataformat(::ThatEndpoint, ::Type{String}) = RawFormat().
RestClient.AbstractFormat — Type
AbstractFormatAbstract supertype for response formats.
Typically, you will want to create a singleton subtype and then implement the following methods for it:
- An
interpretresponsemethod so a response in that format can be parsed/interpreted as a specific type. - A
writepayloadmethod so data can be sent in that format. - A
mimetypemethod so that appropriate headers can be set when sending or receiving data in this format.
See also: RawFormat, JSONFormat.
RestClient.RawFormat — Type
RawFormat <: AbstractFormatSingleton type for raw text or bytes: strings and byte vectors are sent and received as-is, numbers as their decimal text. Other types need a format of their own.
RestClient.UnspecifiedFormat — Type
UnspecifiedFormat <: AbstractFormatThe format of a type that declares none, given by the default dataformat(::Type). An endpoint takes it as its API's format (see @globalconfig), which is RawFormat unless declared otherwise.
RestClient.JSONFormat — Type
JSONFormat <: AbstractFormatSingleton type for JSON request/response formats, read and written with JSON.jl (which must be loaded).
RestClient.XMLFormat — Type
XMLFormat <: AbstractFormatSingleton type for XML request/response formats.
RestClient.FormFormat — Type
FormFormat <: AbstractFormatapplication/x-www-form-urlencoded payloads.
RestClient.MultipartFormat — Type
MultipartFormat <: AbstractFormatmultipart/form-data payloads. Each property of the serialised value becomes a MIME part, encoded with the field type's own dataformat.
RestClient.MultipartFile — Type
MultipartFile(data; filename = nothing, mimetype = "application/octet-stream")A file in a @multipartdef payload: data (bytes, a string, or an IO) sent with the given filename (by default, its field's name) and Content-Type, given as a string or a MIME.
Throws an ArgumentError if mimetype contains a line break.
Example
@multipartdef struct Upload
report::MultipartFile
end
Upload(report = MultipartFile(read("q3.csv"); filename = "q3.csv", mimetype = "text/csv"))RestClient.dataformat — Function
dataformat([endpoint::AbstractEndpoint], ::Type{T}) -> AbstractFormatReturn the expected format that T is represented by in requests to and responses from endpoint.
A type without a format of its own has UnspecifiedFormat, which for an endpoint becomes its API's format: RawFormat, unless declared otherwise with @globalconfig … format = … (see @globalconfig). Bytes and IO are always RawFormat, as is any type whose own dataformat method says so, and a string is text whatever the API's format (though a Vector{String} takes it).
A dataformat(::Type) method is automatically defined when invoking @jsondef.
RestClient.interpretresponse — Function
interpretresponse(data::AbstractVector{UInt8}, fmt::AbstractFormat, ::Type{T}) -> value::TInterpret data as a response of type T according to fmt.
For JSONFormat, the methods are implemented in the JSON.jl package extension.
A method must leave data intact, as a body that fails to read is tried as the endpoint's errortype, and kept in the error raised. Beware String(data), which takes data's memory and leaves it empty: use String(copy(data)).
RestClient.writepayload — Function
writepayload(dest::IO, fmt::AbstractFormat, data)Write data to dest according to fmt.
RestClient.mimetype — Function
mimetype(fmt::AbstractFormat, ::Type{T}) -> Union{String, MIME, Nothing}
mimetype(endpoint::AbstractEndpoint, fmt::AbstractFormat, ::Type{T}) -> Union{String, MIME, Nothing}The media type a T in fmt is labelled with, or nothing for none: the Content-Type of a payload, and the Accept of a result. An endpoint labels a type as its format does, unless a method for it (or its supertype) says otherwise, such as for an API's vendor type:
RestClient.mimetype(::GitHubAPI, ::JSONFormat, ::Type) = MIME("application/vnd.github+json")RawFormat has no label: a raw payload is sent as text/plain text or application/octet-stream bytes, and a raw result accepts anything.