View Source Tesla.Middleware.JSON (tesla v1.11.2)

Encode requests and decode responses as JSON.

This middleware requires Jason (or other engine) as dependency.

Remember to add {:jason, ">= 1.0"} to dependencies. Also, you need to recompile Tesla after adding :jason dependency:

mix deps.clean tesla
mix deps.compile tesla

If you only need to encode the request body or decode the response body, you can use Tesla.Middleware.EncodeJson or Tesla.Middleware.DecodeJson directly instead.

Examples

defmodule MyClient do
  use Tesla

  plug Tesla.Middleware.JSON # use jason engine
  # or
  plug Tesla.Middleware.JSON, engine: JSX, engine_opts: [strict: [:comments]]
  # or
  plug Tesla.Middleware.JSON, engine: Poison, engine_opts: [keys: :atoms]
  # or
  plug Tesla.Middleware.JSON, decode: &JSX.decode/1, encode: &JSX.encode/1
end

Options

  • :decode - decoding function
  • :encode - encoding function
  • :encode_content_type - content-type to be used in request header
  • :engine - encode/decode engine, e.g Jason, Poison or JSX (defaults to Jason)
  • :engine_opts - optional engine options
  • :decode_content_types - list of additional decodable content-types

Summary

Functions

Decode response body as JSON.

Encode request body as JSON.

Functions

@spec decode(
  Tesla.Env.t(),
  keyword()
) :: Tesla.Env.result()

Decode response body as JSON.

It is used by Tesla.Middleware.DecodeJson.

@spec encode(
  Tesla.Env.t(),
  keyword()
) :: Tesla.Env.result()

Encode request body as JSON.

It is used by Tesla.Middleware.EncodeJson.