Ellin.com
Not Very Interesting
HTTPie

This page was converted from my old blog and hasn’t been reviewed. If you see an error please let me know in the comments.

I can never remember how to use CURL. Whenever I want to send some data I end up having to use google or try and dig through the terrible man pages. LMGTFY

Today I leanred about a new tool called HTTPie. HTTPie is a command line tool that is way easier to use and understand than CURL.

Install it on the Mac

brew install httpie

Post some data with CURL.

curl -d "param1=value1&param2=value2" -X POST http://localhost:3000/data

The equivalent using HTTP Pie. The == operator is used to indicate a query string parameter.

http POST http://localhost:3000/data param1==value param2==value2

Often as developers, we are testing code against localhost. Fortunately, there is a shorthand syntax for this common occurrence.

http POST :3000/data param1==value param2==value2

Want to post a file? Use standard Unix pipes

http POST :3000/data < file.json

Since JSON is commonly used during REST operations HTTP Pie helps us with that as well.

Suppose we want to send a document as shown below.

{
    "param1": "value1",
    "param2": "value2"
}

by using the = sign we can tell HTTP Pie to construct the document.

$ http PUT :3000 param1=value1 param2=value2

HTTP Pie will add the default encoding for JSON

PUT / HTTP/1.1
Accept: application/json
Accept-Encoding: gzip, deflate
Content-Type: application/json
{ “param1”: “value1”, “param2”: “value2” }

Its even possible to create nested JSON structures such as

{
    "age": 29,
    "hobbies": [
        "http",
        "pies"
    ],
    "description": "John is a nice guy who likes pies.",
    "married": false,
    "name": "John",
    "bookmarks": {
        "HTTPie": "http://httpie.org",
    }
}

The above example from the HTTP Pie documentation is constructed using

http PUT api.example.com/person/1 \
    name=John \
    age:=29 married:=false hobbies:='["http", "pies"]' \  # Raw JSON
    description=@about-john.txt \   # Embed text file
    bookmarks:=@bookmarks.json      # Embed JSON file

The := operator is used for nonstring values and when you would like to embed a JSON file into the request.

Ever want to post a form with CURL? LMGTFY

curl -d "param1=value1&param2=value2" -H "Content-Type: application/x-www-form-urlencoded" -X POST http://localhost:3000/data

The below is the equivalent with HTTP Pie

http --form POST :3000/data param1=value1 param2=value2

I never knew about this tool before today. In the past, I would resort to browser plugins like PostMan in order to make testing my services easier. Now that I know about HTTP Pie, I think I will try and make use of it more often.

Post by Jeffrey Ellin


Last modified on 2018-03-16

comments powered by Disqus