• Stars
    star
    725
  • Rank 62,504 (Top 2 %)
  • Language
    Elixir
  • License
    The Unlicense
  • Created about 12 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

[Deprecated because ibrowse is not maintained] HTTP client for Elixir (use Tesla please)

hex.pm version hex.pm downloads API Docs unlicense

HTTPotion

HTTP client for Elixir, based on ibrowse. Continues the HTTPun tradition of HTTParty, HTTPretty, HTTParrot and HTTPie.

Note: unfortunately, ibrowse seems a bit buggy and not super actively maintained. You might want to check out Tesla with hackney instead, and this cert verification setup.

Installation

Add HTTPotion to your project's dependencies in mix.exs:

  defp deps do
    [
      {:httpotion, "~> 3.1.0"}
    ]
  end

  def application do
    [ applications: [:httpotion] ]
    # Application dependency auto-starts it, otherwise: HTTPotion.start
  end

And fetch your project's dependencies:

$ mix deps.get

Usage

Note: You can load HTTPotion into the Elixir REPL by executing this command from the root of your project:

$ iex -S mix

Note: HTTPotion now enables certificate verification by default, using a few default CA bundle paths (/etc/ssl/cert.pem etc.) or the certifi package (which is not a mandatory dependency).

Some basic examples:

iex> response = HTTPotion.get "https://httpbin.org/get"
%HTTPotion.Response{
  body: "{\n…",
  headers: %HTTPotion.Headers{ hdrs: %{"connection" => "keep-alive", …} },
  status_code: 200
}

iex> HTTPotion.Response.success?(response)
true

# Response headers are wrapped to allow case-insensitive access (and to support both atoms and strings)
iex> response.headers[:sErvEr]
"meinheld/0.6.1"

iex> response.headers["ConTenT-TyPe"]
"application/json"

# Response headers can have multiple values
iex> response = HTTPotion.get "https://httpbin.org/response-headers?foo=1&foo=2&bar=1"
%HTTPotion.Response{
  body: "{\n…",
  headers: %HTTPotion.Headers{ hdrs: %{"foo" => ["1", "2"], "bar" => "1" …} },
  status_code: 200
}

# You can provide a map for the query string
iex> HTTPotion.get("https://httpbin.org/get", query: %{page: 2})
%HTTPotion.Response{body: "…", headers: …, status_code: 200}

# Follow redirects
iex> HTTPotion.get("https://httpbin.org/redirect-to?url=http%3A%2F%2Fexample.com%2F", follow_redirects: true)
%HTTPotion.Response{body: "…<title>Example Domain</title>…", headers: …, status_code: 200}

# Send form data
iex> HTTPotion.post "https://httpbin.org/post", [body: "hello=" <> URI.encode_www_form("w o r l d !!"),
  headers: ["User-Agent": "My App", "Content-Type": "application/x-www-form-urlencoded"]]
%HTTPotion.Response{body: "…", headers: …, status_code: 200}

# Use a custom method
iex> HTTPotion.request :propfind, "http://httpbin.org/post", [body: "I have no idea what I'm doing"]
%HTTPotion.Response{body: "…", headers: …, status_code: 405}

# Send Basic auth credentials
iex> HTTPotion.get "https://httpbin.org/basic-auth/foo/bar", [basic_auth: {"foo", "bar"}]
%HTTPotion.Response{
  body: "…",
  headers: %HTTPotion.Headers { hdrs: %{"Access-Control-Allow-Credentials": "true", …} },
  status_code: 200
}

# Pass options to ibrowse (note that it usually takes char_lists, not elixir strings)
iex> HTTPotion.get "https://check-tls.akamaized.net", [ ibrowse: [ ssl_options: [ versions, [:'tlsv1.1'] ] ] ]
%HTTPotion.Response{body: "…TLS SNI: present - Check TLS - (https,tls1.1,ipv4)…", headers: …, status_code: 200}

# Change the timeout (default is 5000 ms)
iex> HTTPotion.get "https://example.com", [timeout: 10_000]

# If there is an error a `HTTPotion.ErrorResponse` is returned
iex> HTTPotion.get "http://localhost:1"
%HTTPotion.ErrorResponse{message: "econnrefused"}

# You can also raise `HTTPError` with the `bang` version of request
iex> HTTPotion.get! "http://localhost:1"
** (HTTPotion.HTTPError) econnrefused

The Response is a struct, you can access its fields like: response.body.

response.headers is a struct (HTTPotion.Headers) that wraps a map to provide case-insensitive access (so you can use response.headers[:authorization] and it doesn't matter if the server returned AuThOrIZatIOn or something).

HTTPError is an exception that happens when a bang request (request! / get! / …) fails.

Available options and their default values:

{
  body: "",                # Request's body contents, e.g. "{json: \"string\"}"
  headers: [],             # Request's headers, e.g. [Accept: "application/json"]
  query: nil,              # Query string, e.g. %{page: 1}
  timeout: 5000,           # Timeout in milliseconds, e.g. 5000
  basic_auth: nil,         # Basic auth credentials, e.g. {"username", "password"}
  stream_to: nil,          # A process to stream the response to when performing async requests
  direct: nil,             # An ibrowse worker for direct mode
  ibrowse: [],             # ibrowse options
  auto_sni: true,          # Whether TLS SNI should be automatically configured (does URI parsing)
  follow_redirects: false, # Whether redirects should be followed
}

Metaprogramming magic

You can extend HTTPotion.Base to make cool HTTP API wrappers (this example uses Poison for JSON):

defmodule GitHub do
  use HTTPotion.Base

  def process_url(url) do
    "https://api.github.com/" <> url
  end

  def process_request_headers(headers) do
    Dict.put headers, :"User-Agent", "github-potion"
  end

  def process_response_body(body) do
    body |> Poison.decode!
  end
end
iex> GitHub.get("users/unrelentingtech").body["public_repos"]
233

Read the source to see all the hooks.

Keep in mind that process_response_body and process_response_chunk get iodata. By default, they call IO.iodata_to_binary. But efficient parsers like Poison can work directly on iodata.

Asynchronous requests

You can get the response streamed to your current process asynchronously:

iex> HTTPotion.get "http://httpbin.org/get", [stream_to: self]
%HTTPotion.AsyncResponse{id: -576460752303419903}

iex> flush
%HTTPotion.AsyncHeaders{
  id: -576460752303419903,
  status_code: 200,
  headers: %HTTPotion.Headers{ hdrs: %{"connection" => "keep-alive", …} }
}
%HTTPotion.AsyncChunk{
  id: -576460752303419903,
  chunk: "{\n…"
}
%HTTPotion.AsyncEnd{
  id: -576460752303419903
}

Note that instead of process_response_body, process_response_chunk is called on the chunks before sending them out to the receiver (the stream_to process).

Direct access to ibrowse workers

ibrowse allows you to use its separate worker processes directly. We expose this functionality through the direct option.

Don't forget that you have to pass the URL to the worker process, which means the worker only communicates with one server (domain!)

iex> {:ok, worker_pid} = HTTPotion.spawn_worker_process("http://httpbin.org")

iex> HTTPotion.get "httpbin.org/get", [direct: worker_pid]
%HTTPotion.Response{body: "…", headers: ["Connection": "close", …], status_code: 200}

You can even combine it with async!

iex> {:ok, worker_pid} = HTTPotion.spawn_worker_process("http://httpbin.org")

iex> HTTPotion.post "httpbin.org/post", [direct: worker_pid, stream_to: self, headers: ["User-Agent": "hello it's me"]]
%HTTPotion.AsyncResponse{id: {1372,8757,656584}}

Type analysis

HTTPotion contains typespecs so your usage can be checked with dialyzer, probably via dialyxir or elixir-ls.

HTTPotion's tests are checked with dialyxir.

Contributing

Please feel free to submit pull requests!

By participating in this project you agree to follow the Contributor Code of Conduct.

License

This is free and unencumbered software released into the public domain.
For more information, please refer to the UNLICENSE file or unlicense.org.

More Repositories

1

systemstat

Rust library for getting system information | also on https://codeberg.org/valpackett/systemstat
Rust
564
star
2

awesome-gtk

List of awesome GTK (3/4) applications
534
star
3

freepass

[DEPRECATED] password manager thing
Rust
310
star
4

cssprefixer

[DEPRECATED] A tool that rewrites your CSS files, adding vendor-prefixed versions of CSS3 rules.
Python
191
star
5

zshuery

[DEPRECATED] Minimal zsh framework
Shell
145
star
6

galacritty

[Abandoned experiment] GTK terminal emulator based on Alacritty [USE WEZTERM!]
Rust
145
star
7

soundfixer

A WebExtension that lets you fix sound problems in e.g. YouTube videos
JavaScript
137
star
8

SwiftCBOR

A CBOR implementation for Swift
Swift
127
star
9

clj-http-fake

Helper for faking clj-http requests | now on https://codeberg.org/valpackett/clj-http-fake
126
star
10

evscript

A tiny sandboxed Dyon scripting environment for evdev input devices that lets you do e.g. xcape in Wayland | now on https://codeberg.org/valpackett/evscript
122
star
11

magicbane

A web framework that integrates Servant, EKG, fast-logger, wai-cli… | now on https://codeberg.org/valpackett/magicbane
120
star
12

unixbar

Rust library for creating output for UNIX-style desktop bars like i3bar/swaybar, dzen2, lemonbar | now on https://codeberg.org/valpackett/unixbar
119
star
13

secstr

Secure string library for Rust | now on https://codeberg.org/valpackett/secstr
97
star
14

django-mode

Django mode and snippets for Emacs
Emacs Lisp
96
star
15

markbox

[DEPRECATED] A blogging engine for Dropbox based on Markdown
Python
94
star
16

intero.nvim

Haskell+Neovim lightning fast autocompletion and other IDE functionality
Vim Script
79
star
17

ring-ratelimit

Rate limiting middleware for Clojure Ring | now on https://codeberg.org/valpackett/ring-ratelimit
79
star
18

octohipster

[UNMAINTAINED] A hypermedia REST HTTP API library for Clojure
Clojure
75
star
19

transmitter

A WebExtension for the Transmission BitTorrent client
JavaScript
75
star
20

ringfinger

[DEPRECATED] Fun, fast, secure web development on top of Clojure/Ring
Clojure
67
star
21

rxjava-http-tail

RxJava-based HTTP log following library | now on https://codeberg.org/valpackett/rxjava-http-tail
65
star
22

freshcerts

ACME certificate protocol (Let's Encrypt) proxy client with a dashboard and monitoring
Ruby
60
star
23

rusty-sandbox

A sandboxing library for Rust | now on https://codeberg.org/valpackett/rusty-sandbox
58
star
24

capsicumizer

Run anything (like full blown GTK apps) under Capsicum
C++
54
star
25

pcre-heavy

A Haskell regular expressions library that doesn't suck | now on https://codeberg.org/valpackett/pcre-heavy
52
star
26

sweetroll

A personal website / #indieweb engine [OLD VERSION]
Haskell
51
star
27

micro-panel

Admin panel for micropub and microformats2 | also on: https://codeberg.org/valpackett/micro-panel
JavaScript
45
star
28

filesortd

Rule-based file sorting (like Hazel) with a Ruby DSL
Ruby
38
star
29

interactor

A Rust library for simple (usually command-line) user interaction | now on https://codeberg.org/valpackett/interactor
33
star
30

sweetroll2

A powerful micro/blogging engine with IndieWeb features (abandoned)
Elixir
28
star
31

hs-duktape

Haskell bindings for a very compact embedded JavaScript engine | now on https://codeberg.org/valpackett/hs-duktape
23
star
32

clj-configurator

A powerful yet simple configuration library for Clojure | now on https://codeberg.org/valpackett/clj-configurator
22
star
33

sweetreaction

A collection of React macros for Sweet.js - Actually react is bad
JavaScript
20
star
34

443d

TLS with HTTP/2 proxying, demultiplexed with SSH, on your port 443
Go
19
star
35

neojamvm

JamVM (lightweight Java Virtual Machine) but built with CMake
C
18
star
36

eslint-plugin-pug

An ESLint plugin for linting inline scripts in Pug files
JavaScript
17
star
37

gitson

A simple document store library for Git + JSON. | now on https://codeberg.org/valpackett/gitson
17
star
38

soad

SOcket Activator/Deactivator: like inetd but not really | now on https://codeberg.org/valpackett/soad
16
star
39

numbernine

Attempt at a desktop shell and stuff; abandoned in favor of https://github.com/DankBSD/waysmoke
D
16
star
40

pysectools

A small Python library that contains various security things
Python
15
star
41

weston-rs

[UNMAINTAINED] Rust bindings to libweston(-desktop) of Weston, the reference Wayland compositor
Rust
15
star
42

tiny-nix-ipc

Minimal Rust wrapper for using sockets as IPC with file descriptor passing | now on https://codeberg.org/valpackett/tiny-nix-ipc
15
star
43

micloudfaker

Use Xiaomi qmi.powerstrip.v1 offline | now on https://codeberg.org/valpackett/micloudfaker
14
star
44

shmemfdrs

Rust crate that creates anonymous shared memory file descriptors for IPC using memfd/SHM_ANON/shm_open | now on https://github.com/valpackett/shmemfdrs
13
star
45

ergonice

69-key split mechanical keyboard (PCB, case, firmware) | now on https://codeberg.org/valpackett/ergonice
13
star
46

gosemver

Semantic Versioning parsing, sorting, constraints and output library for the Go language
Go
13
star
47

indieweb-components

VanillaJS-based Web Components for the IndieWeb
JavaScript
13
star
48

wai-cli

Command line runner for Wai apps (using Warp) with TLS, CGI, socket activation & graceful shutdown | now on https://codeberg.org/valpackett/wai-cli
12
star
49

microformats2-parser

A Microformats 2 parser for Haskell | now on https://codeberg.org/valpackett/microformats2-parser - GH used for Actions only
Haskell
12
star
50

mail2elasticsearch

Fast ElasticSearch indexer for MIME email
Go
12
star
51

xvmmgr

A simple tray icon program for integrating a UNIX system running on Hyper-V or VirtualBox into the Windows desktop
PowerShell
11
star
52

sandblast

C
10
star
53

clj-bonecp-url

Clojure wrapper for BoneCP (DEPRECATED) that also parses database URLs | now on https://codeberg.org/valpackett/clj-bonecp-url
10
star
54

colorhash256

Like Chroma-Hash, but with ANSI terminal colors | now on https://codeberg.org/valpackett/colorhash256
9
star
55

broccoli-webpack

A Broccoli plugin for webpack
JavaScript
9
star
56

docker-freebsd-cross

Docker image for cross-compiling to FreeBSD. With pkg!!
Dockerfile
9
star
57

rusterpassword

A Rust implementation of the Spectre / Master Password algorithm | now on https://codeberg.org/valpackett/rusterpassword
9
star
58

appnetdav

[DEPRECATED] A WebDAV proxy for the App.net File API
Ruby
8
star
59

pebble-music-library

Music library browser for the Pebble smartwatch.
Java
8
star
60

less-mode

Less major mode for Emacs
Emacs Lisp
8
star
61

rpi-touchscreen-mainline

Building 7" Official Raspberry Pi Touchscreen drivers on vanilla mainline Linux kernels
C
8
star
62

antigravity

Antigravity lets you share files through App.net from an Android device - Press F for App.net
Java
7
star
63

labs

experiments
JavaScript
7
star
64

classyclock

Class schedule watchface for the Pebble smartwatch
HTML
6
star
65

gazeta

[DEPRECATED] A publish-subscribe (PubSub) framework for Clojure and ClojureScript, based on core.async.
Clojure
6
star
66

conatra

Sinatra-style syntax for the Internet of Things (CoAP/CoRE, Arduino)
Arduino
6
star
67

mf2sql

PostgreSQL schema for storing microformats2 JSON objects
PLpgSQL
6
star
68

startproject

Simple project starter for Emacs
Emacs Lisp
6
star
69

mason-ry

A Polymer element / web component that wraps Masonry, a layout library
HTML
6
star
70

http-link-header

A Haskell library for the HTTP Link header as specified in RFC 5988 "Web Linking" | now on https://codeberg.org/valpackett/http-link-header
6
star
71

broccoli-source-map

A Broccoli plugin for inlining or extracting sourcemaps.
JavaScript
5
star
72

feedrobot

[DEPRECATED] RSS/Atom to App.net Private Messages bot
Ruby
5
star
73

es-module-devserver

Simple static server middleware with ES Module path resolution | now on https://codeberg.org/valpackett/es-module-devserver
5
star
74

damnx509

A simple CLI for managing a small X.509 Certificate Authority | now on https://codeberg.org/valpackett/damnx509
5
star
75

dankshell

Go to https://github.com/myfreeweb/numbernine instead
Rust
5
star
76

modx-uncacher

Smarter cache cleaning for MODX Revolution
PHP
5
star
77

codeflask-element

A micro code-editor in a Custom Element (v1)
JavaScript
5
star
78

weston-extra-dip

[UNMAINTAINED] A pack of plugins for the Weston compositor
C++
5
star
79

wideplate

A multi-column responsive/adaptive CSS layout starter kit
CSS
5
star
80

sellout

IndieAuth/Micropub for static (Zola+GitHub) websites, runnable on Lambda
Python
4
star
81

sweetbuild

A Sweet.js DSL for Broccoli, the best frontend asset pipeline.
JavaScript
4
star
82

XmlDocTable

C# XML Documentation to LaTeX table converter based on Roslyn
C#
4
star
83

attrsets

Rust proc macro for defining multiple variants of a struct/enum with different attribute annotations e.g. for multiple Serde serializations | now on https://codeberg.org/valpackett/attrsets
4
star
84

devd-rs

Rust crate for listening to FreeBSD devd's device attach-detach notifications | now on https://codeberg.org/valpackett/devd-rs
4
star
85

node-red-contrib-nut-ups

Node-RED node that gets UPS data via NUT (Network UPS Tools).
HTML
4
star
86

loginw

Generic setuid wrapper for Wayland compositors
Rust
4
star
87

pdfork

A Rust fork wrapper that uses process descriptors (pdfork) on FreeBSD and normal fork elsewhere. | now on https://codeberg.org/valpackett/pdfork
4
star
88

indieweb-algorithms

A collection of implementations of IndieWeb algorithms in Haskell | now on https://codeberg.org/valpackett/indieweb-algorithms
4
star
89

nitm

Nobody In The Middle – Test if a web page looks the same via different Tor circuits
Python
3
star
90

appvertise

[DEPRECATED] Experimental ad network based on App.net and Bitcoin
Ruby
3
star
91

usmc-kmod

FreeBSD Kernel module for doing ARMv8 Secure Monitor Calls from userspace | now on https://codeberg.org/valpackett/usmc-kmod
3
star
92

imgroll

Image optimizer and nice metadata extractor (with AWS Lambda support)
Rust
3
star
93

clj-dcss

A Clojure library for parsing and processing Dungeon Crawl Stone Soup data.
Clojure
3
star
94

webgradients

A tool for creating simple and smooth PNG linear gradients with plain HTTP requests. 2.0.
Go
3
star
95

crawllog

A webapp that posts your Dungeon Crawl Stone Soup game logs (morgue files) to your website using Micropub
Python
3
star
96

supportappnet

[DEPRECATED] App.net-based support/feedback (inspired by services like Get Satisfaction).
Ruby
3
star
97

libwebp-sys

Rust bindings to libwebp | now on https://codeberg.org/valpackett/libwebp-sys
Rust
3
star
98

broccoli-brotli

Broccoli extension to apply brotli compression
JavaScript
3
star
99

statusboardthings

My widgets for Panic's Status Board for iPad - Press F for Status Board
Factor
3
star
100

ex_http_link

An Elixir library for the HTTP Link header as specified in RFC 5988 "Web Linking" | now on https://codeberg.org/valpackett/ex_http_link
3
star