BodyProvider

public struct BodyProvider

A type that produces the body of a request and updates the header of a request accordingly.

A BodyProvider implements a function that takes an inout Header and produces a RequestBody. In the body(updating:) method, the provider should construct the RequestBody and update the Content-Type of the provided Header. The provider can also set any other relevant fields in the header.

Several predefined BodyProviders are provided for text bodies and JSON bodies.

Creating a BodyProvider

The body(updating:) method is defined when the BodyProvider is initialised as a closure. The method is somewhat odd because it doesn’t take any data to convert to a RequestBody as input. In your BodyProviders you should capture the input data in the closure provided at initialization. This means that most BodyProviders will be provided by factory functions that take the input data and construct a new body provider using it.

When implementing a provider, ensure that updates to the provided header are only applied when any throwing functions have succeeded. Otherwise you may end up in the situation where the header of a request is updated but its body has not been created because an error was thrown during creation.

  • An empty BodyProvider. This provider never throws an error, removes the Content-Type field of the header and always produces a RequestBody.none.

    Declaration

    Swift

    static let none: BodyProvider
  • A body provider that wraps some raw data.

    This provider never throws an error.

    Declaration

    Swift

    static func raw(data: Data, contentType: MediaType = .binary) -> BodyProvider

    Parameters

    data

    The data to set as the body.

    contentType

    The Content-Type of data. Defaults to application/octet-stream.

  • A body provider that wraps a raw input stream.

    This provider never throws an error.

    Declaration

    Swift

    static func raw(stream: InputStream, contentType: MediaType = .binary) -> BodyProvider

    Parameters

    stream

    The stream to set as the body.

    contentType

    The Content-Type of stream. Defaults to application/octet-stream.

  • A body provider that produces a UTF-8 encoded body.

    Throws

    A TextBodyEncodingError if text is not valid UTF-8 text.

    Declaration

    Swift

    static func text(_ text: String) -> BodyProvider

    Parameters

    text

    The text to set as the body of the request.

  • A body provider that produces a JSON body representation of a value.

    Throws

    Any error that can be thrown by JSONEncoder.

    Declaration

    Swift

    static func json<T>(encoded value: T, using encoder: JSONEncoder = JSONEncoder()) -> BodyProvider where T : Encodable

    Parameters

    value

    The value to encode as the request’s body.

    encoder

    The encoder to encode value with. Defaults to JSONEncoder().