Blog post
HTTPie is a command line HTTP client. The goal is to make the CLI’s interaction with Web services as friendly as possible. It provides a simple HTTP command that allows you to send any HTTP request in a simple, natural expression, and output results with code highlighting. HTTPie can be used in testing, debugging, and generic HTTP interaction scenarios
Main Functions and Features
- Natural and simple command statements
- Format and highlight the output
- Built-in JSON support
- Form and file uploads
- Supports HTTPS, proxy, and authorization authentication
- Support for diverse request data formats
- Customize headers
- Persistent Sessions store
- similar
wget
Download mode of - Compatible with Python 2.6, 2.7, and 3.x
- Supports Linux, macOS and Windows operating systems
- Plug-in support
- Detailed documentation
- Complete test case coverage
The installation
macOS
Homebrew is recommended for macOS:
brew install httpie
Copy the code
MacPorts are also available:
port install httpie
Copy the code
Linux
Most Linux builds provide package management components that you can use to install:
# Build on Debian Linux, such as Ubuntu
apt-get install httpie
# Build based on RPM Linux
yum install httpie
# Arch Linux system
pacman -S httpie
Copy the code
Windows and other
Using PIP is universal (can be used on Windows, MacOS, Linux…) In addition, the installation method of the latest version installation package is provided
# Make sure you are using the latest PIP and SetupTools:
pip install --upgrade pip setuptools
pip install --upgrade httpie
Copy the code
Development version
The latest development version can be installed directly from Github
# Homebrew
brew install httpie --HEAD
# pip
pip install --upgrade https://github.com/jkbrzt/httpie/archive/master.tar.gz
Copy the code
Python version
Although compatible with Python 2.6, 2.7, it is recommended to use the latest version of Python 3.x to install HTTPie if possible. This will ensure that newer features, such as SNI, are available right out of the box. Python 3 has become the default Python release above Homebrew 0.9.4. You can use HTTP –debug to see the Python version used by HTTPie
use
Easiest to use:
http httpie.org
Copy the code
Use grammar:
http [flags] [METHOD] URL [ITEM [ITEM]]
Copy the code
You can also use HTTP –help to see more usage:
example
Custom HTTP methods, HTTP headers, and JSON data:
http PUT example.org X-API-Token:123 name=John
Copy the code
Form submission:
http -f POST example.org hello=World
Copy the code
Use an output parameter -v to view the request information (no request information is displayed by default) :
http -v example.org
Copy the code
Send a comment to the issue using the Github API (authorization validation parameter required) :
http -a USERNAME POST https://api.github.com/repos/jkbrzt/httpie/issues/83/comments body='HTTPie is awesome! :heart:'
Copy the code
Redirects files to be uploaded using command line input:
http example.org < file.json
Copy the code
Download files using wGET style:
http --download example.org/file
Copy the code
Persistent communication between requests to the same host using a command session:
http --session=logged-in -a username:password httpbin.org/get API-Key:123
http --session=logged-in httpbin.org/headers
Copy the code
Custom request host header:
http localhost:8000 Host:example.com
Copy the code
HTTP method
The HTTP method name precedes the URL parameter:
http DELETE example.org/todos/7
Copy the code
This looks just like the text sent by a native HTTP request:
DELETE /todos/7HTTP / 1.1Copy the code
The request URL
The only required argument to HTTPie is the request URL. The default, unsurprisingly, is http://. You can request -http example.org by default, which is fine
The Querystring parameters
If you need to build URLs manually on the command line, you might find it convenient to add parameters using param==value so that you don’t have to worry about escaping the link string & on the command line, and of course special characters in parameters will be automatically escaped (unless already escaped). Search for HTTPie logo in Google Images with the following command:
http www.google.com search=='HTTPie logo'tbm==isch GET /? Search = HTTPie + logo&tbm = isch HTTP / 1.1Copy the code
The URL abbreviation for localhost
Also, a localhost abbreviation like curl is supported. This means you can use :3000 instead of http://localhost:3000. If no port number is passed in, 80 will be used by default
HTTP :/foo GET /foo HTTP/1.1 Host: localhostCopy the code
HTTP :3000/bar GET /bar HTTP/1.1 Host: localhost:3000Copy the code
HTTP: GET/HTTP/1.1 Host: localhostCopy the code
Customize the default schema
You can specify other non-HTTP conjunctions using the –default-scheme
argument
alias https='http --default-scheme=https'
Copy the code
The request item
Different request item types provide a convenient way to specify HTTP headers, simple JSON, form data, files, and URL parameters
The URL argument is followed by key/value pair arguments that are assembled and sent as requests. The different types of key/value pair split symbols are: :, =, :=, @, =@, :=@. The @ split argument represents the file path
Item type | Description (Description) |
---|---|
The HTTP header parameterName:Value |
Arbitrary HTTP headers, such as:X-API-Token:123 |
The URL parametername==value |
By separator= = Representing a query stringKey/value 对 |
Data fieldsfield=value .[email protected] |
Request a data field that will be serialized to JSON by default, or form type form-encoded(--form, -f) |
Pure JSON domainfield:=json .field:[email protected] |
When one or more field parameter types need to be specifiedboolean .number . Useful when, for instance: meals: = ‘[” ham “, “spam”]’ or pies: = [1, 2, 3] (note the quotes). |
Form file field | Only if a parameter is passed in--form, -f For examplescreenshot@~/Pictures/img.png The file contents will be serialized intomultipart/form-data send |
Data fields are not the only way to specify requested data; redirecting input is also possible
Character escape rules
You can use \ to escape cases where the separator should not be used. For example, foo\==bar is escaped as a data key-value pair (foo= and bar) instead of a URL parameter
Usually you want to surround values with quotes, such as foo=’bar baz’
If you have a field name or header that starts with a minus sign, you need to put those arguments after a special — to distinguish them from –arguments
HTTP httpbin.org/post -- name-starting-with-dash=foo -Unusual-Header:bar POST/POST HTTP/1.1 -Unusual-Header: bar Content-Type: application/json {"-name-starting-with-dash": "value"
}
Copy the code
JSON
JSON is a common specification for modern Web services, and HTTPie follows its lax data types by default
HTTP PUT example.org name=John [email protected] PUT/HTTP/1.1 Accept: application/json, */* Accept-encoding: gzip, deflate Content-Type: application/json Host: example.org {"name": "John"."email": "[email protected]"
}
Copy the code
The default behavior
If your command contains request item data, it will be serialized as a JSON object by default. The following two headers are automatically added to HTTPie by default, although they can also be repassed
Content-Type | application/json |
---|---|
Accept | application/json, */* |
Clear the JSON
You can use the command line argument –json, -j to explicitly set Accept to application/json regardless of what data is being sent (this is a shortcut, or you can use the normal header annotation: HTTP URL Accept:’application/json, */*’), in addition, HTTPie will try to detect the JSON response, even if the Content-type is abnormal text/plain or unknown
JSON fields that are not strings
Non-string JSON fields use := split, which allows you to embed native pure JSON into result objects, text and native pure JSNO files can also be embedded using =@ and :=G
http PUT api.example.com/person/1 \
name=John \
age:=29 married:=false hobbies:='["http", "pies"]' \ # Raw JSON
[email protected] \ # Embed text file
bookmarks:[email protected] # Embed JSON file
PUT /person/1 HTTP/1.1
Accept: application/json, */*
Content-Type: application/json
Host: api.example.com
{
"age": 29."hobbies": [
"http"."pies"]."description": "John is a nice guy who likes pies."."married": false."name": "John"."bookmarks": {
"HTTPie": "http://httpie.org",}}Copy the code
Note, however, that the syntax used in this example can be cumbersome when sending complex data. In this case redirecting the input would be more appropriate:
http POST api.example.com/person/1 < person.json
Copy the code
The form
Submitting a form is very similar to sending a JSON request, usually the only difference is to add an extra –form, -f parameter, which ensures that the data field and Content-Type are set to Application/X-www-form-urlencoded; charset=utf-8
Normal forms
http --form POST api.example.org/person/1 name='John Smith'POST /person/1 HTTP/1.1 Content-type: Application /x-www-form-urlencoded; charset=utf-8 name=John+SmithCopy the code
File upload form
If there is a file field, the serialization method and content type will be multipart/form-data:
http -f POST example.com/jobs name='John Smith' cv@~/Documents/cv.pdf
Copy the code
The above request is the same as the following HTML form sending request:
<form enctype="multipart/form-data" method="post" action="http://example.com/jobs">
<input type="text" name="name" />
<input type="file" name="cv" />
</form>
Copy the code
Note that @ is used to simulate the file upload field, while =@ empowers the file contents as text into the values of the data field
HTTP header
You can add custom Header information in the form of Header:Value annotations
The user-agent HTTP example.org: Bacon / 1.0'Cookie:valued-visitor=yes; foo=bar'\ X - Foo: Bar Referer:http://httpie.org/ GET/HTTP / 1.1 Accept: * / * Accept - Encoding: gzip, deflate cookies: valued-visitor=yes; Foo =bar Host: example.org Referer: http://httpie.org/ user-agent: Bacon/ 1.0x-foo: barCopy the code
The default request header
There are several default request headers that are HTTPie
GET /HTTP / 1.1Accept: * / *Accept-Encoding: gzip, deflate
User-Agent: HTTPie/<version>
Host: <taken-from-URL>
Copy the code
Empty and reset the default header
You can use Header: to cancel several of the default headers above
http httpbin.org/headers Accept: User-Agent:
Copy the code
Both the Accept and User-Agent headers in the request are removed
Use the Header; Adds an empty header. Note that quotation marks must be used
http -v httpbin.org/headers 'Host; 'GET /headers HTTP/1.1 Accept: */* Accept-encoding: gzip, deflate Connection: keep-alive Host: user-agent: HTTPie / 0.9.9...Copy the code
Authorization verification
Currently supported authentication schemes are basic and summary (see more authorization plug-ins), with two identifiers to control authentication:
parameter | instructions |
---|---|
--auth, -a |
theUser name: Password Passed as a key-value pair argument, this can be used if only the username is specified- a user name The password is entered at the following prompt, and the empty password is usedusername: .username:password@hostname Format URL syntax is also supported, and the certificate passes-a Parameters are passed in and have a higher priority |
--auth-type, -A |
Specifies specifies the authentication mechanism.basic (Default) anddigest Two kinds of |
Basic authorization
http -a username:password example.org
Copy the code
Digest authorization
http -A digest -a username:password example.org
Copy the code
Password prompt
http -a username example.org<Paste>
Copy the code
.netrc
Authorization from your ~/.netrc file will also work
cat ~/.netrc
machine httpbin.org
login httpie
password test
http httpbin.org/basic-auth/httpie/testHTTP / 1.1 200 OK [...].Copy the code
Authorization plug-in
The authorization mechanism can be implemented by installing plug-ins, more of which can be found in the Python Package
- httpie-api-auth: ApiAuth
- httpie-aws-auth: AWS / Amazon S3
- httpie-edgegrid: EdgeGrid
- httpie-hmac-auth: HMAC
- httpie-jwt-auth: JWTAuth (JSON Web Tokens)
- httpie-negotiate: SPNEGO (GSS Negotiate)
- httpie-ntlm: NTLM (NT LAN Manager)
- httpie-oauth: OAuth
- requests-hawk: Hawk
HTTP redirection
By default, HTTP redirection does not automatically redirect. After a request is sent, only the first received response is displayed on the command line
http httpbin.org/redirect/3
Copy the code
Jump to the location field in the header
Specifying –follow, -f causes HTTPie to automatically follow the location field in the 30x response header and display the final response
http --follow httpbin.org/redirect/3
Copy the code
Displays the intermediate jump response
If you also want to see more jumps, you can specify the –all argument
http --follow --all httpbin.org/redirect/3
Copy the code
Limit the maximum number of redirects
Change the default maximum of 30 redirects using the –max-redirects=
http --follow --all --max-redirects=5 httpbin.org/redirect/3
Copy the code
The agent
You can specify the proxy server for the respective protocol (which is included in the parameter value to prevent cross-protocol redirection) by adding the parameter –proxy
HTTP - proxy = HTTP: http://10.10.1.10:3128 -- proxy = HTTPS: https://10.10.1.10:1080 example.orgCopy the code
Adding BASIC Authorization
HTTP - proxy = HTTP: http://user:[email protected]:3128 example.orgCopy the code
The environment variable
Proxies can also be configured by setting the HTTP_PROXY and HTTPS_PROXY environment variables. The underlying Request library will also use these proxy configurations. If you want to specify that some hosts do not use proxies, you can do so by adding the NO_PROXY parameter
In your ~/.bash_profile file (ZSH is in ~/.zshrc)
exportHTTP_PROXY = http://10.10.1.10:3128exportHTTPS_PROXY = https://10.10.1.10:1080export NO_PROXY=localhost,example.com
Copy the code
Socks
To enable SOCKS proxy support use the PIP install requests[SOCKS] library
pip install -U requests[socks]
Copy the code
The usage is the same as for other types of agents:
http --proxy=http:socks5://user:pass@host:port --proxy=https:socks5://user:pass@host:port example.org
Copy the code
HTTPS
Server SSL certificate verification
Skip host SSL authentication with –verify=no (default: yes)
http --verify=no https://example.org
Copy the code
Customize THE CA package
Use –verify=
to specify the PATH of the CA authentication package
http --cert=client.pem https://example.org
Copy the code
Client SSL certificate
Using the client SSL certificate for SSL communication, you can specify the certificate file path with the –cert parameter
http --cert=client.pem https://example.org
Copy the code
If the certificate does not contain a private key, you can specify the path to the key file using the –cert-key parameter
http --cert=client.crt --cert-key=client.key https://example.org
Copy the code
SSL version
The — SSL =
# specify vulnerable SSL V3 protocol to communicate with older servers
http --ssl=ssl3 https://vulnerable.example.org
Copy the code
Server Name Indication SNI(Server Name Indication)
If your HTTPie version (which can be viewed using HTTP — DEBUG) is less than 2.7.9, you will need to use SNI to talk to the server again. Then you need to install additional dependencies
pip install --upgrade requests[security]
Copy the code
Use the following command to test SNI support
http https://sni.velox.ch
Copy the code
Output parameters
HTTPie by default prints only the final response and prints it (header, body). You can control the print content with the following parameters:
Command line arguments | describe |
---|---|
–headers, -h | Only the response header is printed |
–body, -b | Only the response body is printed |
–verbose, -v | Print all HTTP requests back and forth. This is enabled by default--all parameter |
The –verbose parameter is useful when debugging requests or generating documents
HTTP --verbose PUT httpbin.org/put hello=world PUT/PUT HTTP/1.1 Accept: application/json, */* Accept-encoding: Gzip, deflate Content-type: application/json Host: httpbin.org user-agent: HTTPie/0.2.7dev {"hello": "world"
}
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 477
Content-Type: application/json
Date: Sun, 05 Aug 2012 00:25:23 GMT
Server: gunicorn/0.13.4
{
[…]
}
Copy the code
What part of the HTTP request should be printed out
All of the HTTP output options are shortcuts to the more powerful –print, -p argument. –print, -p accepts a string, each letter of which represents the following part of the HTTP
character | On behalf of |
---|---|
H |
Request header |
B |
Request body |
h |
Response headers |
b |
Response body |
Print request and response headers:
http --print=Hh PUT httpbin.org/put hello=world
Copy the code
Look at the request/response in the middle
Use the –all parameter to view all information in HTTP traffic. Intermediate HTTP traffic includes following redirects (using the parameter –follow) and first unauthorized requests using HTTP digest authorization (using the parameter –auth=diggest).
Includes all response information up to the final response
http --all --follow httpbin.org/redirect/3
Copy the code
By default, the intermediate request/response will be formatted with the value specified by –print, which can be specified by –history-print, which has the same parameters as –print, which has the same value. But this is only for intermediate requests
The intermediate request/response information is formatted with H and the final request/response information is formatted with Hh:
http -A digest -a foo:bar --all -p Hh -P H httpbin.org/digest-auth/auth/foo/bar
Copy the code
Conditional body content download
As an optimization, the response body is downloaded only as part of the output, similar to HEAD requests (except HEAD can be used in any HTTP request).
For example, if an API is updated and returns the entire resource, you are only interested in the status code in the response header:
http --headers PATCH example.org/Really-Huge-Resource name='New Name'
Copy the code
Since we set it to print only headers, the server connection will be closed when the response header is received, and bandwidth and time won’t be wasted downloading the response body, so you don’t have to worry. The response header will always be downloaded whether it is part of the output or not
Redirect input
Passing in the request data directly from the STDIN (standard input) pipeline is what most people think is a better approach. This data is buffered and can be used as a request body without any more work. There are several useful ways to use pipes:
Redirection from a file
http PUT example.com/person/1 X-API-Token:123 < person.json
Copy the code
Or output from other programs
grep '401 Unauthorized' /var/log/httpd/error_log | http POST example.org/intruders
Copy the code
You can also use the echo command to pass simple data
echo '{"name": "John"}' | http PATCH example.com/person/1 X-API-Token:123
Copy the code
You can even use Web services
http GET https://api.github.com/repos/jkbrzt/httpie | http POST httpbin.org/post
Copy the code
You can also use cat to enter multiple lines of text
cat | http POST example.com
<paste>
^D
Copy the code
cat | http POST example.com/todos Content-Type:text/plain
- buy milk
- call parents
^D
Copy the code
In macOS you can use the pbpaste command to send the contents of the clipboard as data
pbpaste | http PUT example.com
Copy the code
The way data is passed through STdin cannot be mixed with the way data fields are specified
echo 'data' | http POST example.org more=data # can't
Copy the code
Retrieves request data from a file
Specify the file path (@/path/to/file) instead of using stdin
One advantage of this approach is that the Content-Type can be automatically set to the corresponding file extension provided. For example, the following request will have a header content-Type: application/ XML
http PUT httpbin.org/put @/data/file.xml
Copy the code
Command line output
HTTPie does a few things by default to make the command line output more readable
Color and formatting
Syntax highlighting is applied to headers and body of HTTP requests. If you don’t like the default color scheme, you can customize it using the –style parameter (use the HTTP –help command to see more options)
The following formatting rules are also used:
- HTTP headers are sorted by name
- JSON data is indented and sorted by key names, and Unicode sequences are converted to actual characters
The following parameters can be used to process the output:
Command line arguments | describe |
---|---|
–pretty=all | Apply color and formatting by default |
–pretty=colors | Color only |
–pretty=format | Apply formatting only |
–pretty=none | Do not use color and formatting, redirection by default |
Binary data
Binary data is disallowed on the command line, which makes it safer to process the binary data returned by the response, and binary data is also disallowed in redirects, but is decorated for output. Once we know that the response body is binary, the connection is closed
http example.org/Movie.mov
Copy the code
You can see the following prompt almost immediately:
HTTP/1.1 200 OK Accept-ranges: bytes content-encoding: gzip content-type: video/ Quicktime Transfer-encoding: chunked +-----------------------------------------+ | NOTE: binary data not shownin terminal |
+-----------------------------------------+
Copy the code
Redirection output
The redirection output uses a different default value than the command line output. The differences are as follows:
- Formatting and color are not used by default (unless
--pretty
Is specified) - Outputs only the response body (unless output parameters are specified)
- Binary results are not prohibited
Piping piping to HTTPie results directly to other programs, and to download files without the need for additional parameters. In most cases only the response body makes sense when the output is redirected
Download a file:
http example.org/Movie.mov > Movie.mov
Copy the code
Download Octocat images, resize them using ImageMagick, and upload them elsewhere:
http octodex.github.com/images/original.jpg | convert - -resize 25% - | http example.org/Octocats
Copy the code
Enforces formatting and color to display requests and responses in less’s pages
http --pretty=all --verbose example.org | less -R
Copy the code
The -r flag tells the less command to parse the color sequence in the HTTPie output
You can use the following bash function code to create a shortcut to call HTTPie page formatting and highlight output:
function httpless {
# `httpless example.org'
http --pretty=all --print=hb "$@" | less -R;
}
Copy the code
Download mode
HTTPie has download mode, similar to the wget command
Use –download and -d to enable the response. The response header will be printed to the command line and the progress bar for downloading the response body will be displayed
HTTP - download https://github.com/jkbrzt/httpie/archive/master.tar.gz HTTP / 1.1 200 OK Content - Disposition: attachment; Filename =httpie-master.tar.gz Content-Length: 257336 Content-Type: Application/X-gzip Downloading 251.30 kB to"httpie-master.tar.gz"
Done. 251.30 kB in2.73862 s (91.76 kB/s)Copy the code
Name of the downloaded file
If the argument –output, -o is not specified, the file name is determined by Content-Disposition, or by the URL and its Content-type, and HTTPie adds a unique suffix if the name is already occupied
Piping at the same time
Even if the response header and progress status are displayed on the command line, you can redirect the response to another application
http -d https://github.com/jkbrzt/httpie/archive/master.tar.gz | tar zxf -
Copy the code
Resume download
If you specify –output, -o, you can resume partial downloads with –continue, -c. Only if the server supports the Range request and the response returns 206 Partial Content. If the server does not support this, only the entire file will be downloaded
http -dco file.zip example.org/file
Copy the code
Other Matters needing attention
--download
Change how only the response body is handled- You can still use custom headers, use sessions,
--verbose, -v
等 --download
It means enable--follow
- HTTPie will return an error status code if the file is not completely downloaded
1
And exit Accept-Encoding
Can’t and--download
Used together
Current response
The responder is downloaded and printed as a block, which allows the program to stream and download without using a lot of memory, whereas if colors and formatting parameters are used, the entire responder is buffered and processed immediately
Disable caching
We can use –stream, -s to do the following:
- The output is updated in smaller chunks without any buffering, making HTTPie behave like
tail -f
command - Even if the output is beautified, the stream is enabled: it is applied to each line of the response and updated immediately. This provides a nice output for long duration requests, such as a Twitter stream API
The sample
Embellished flow response
http --stream -f -a YOUR-TWITTER-NAME https://stream.twitter.com/1/statuses/filter.json track='Justin Bieber'
Copy the code
Small chunks of stream output like tail -f
http --stream -f -a YOUR-TWITTER-NAME https://stream.twitter.com/1/statuses/filter.json track=Apple \
| while read tweet; do echo "$tweet" | http POST example.org/tweets ; done
Copy the code
The session
By default, requests from each HTTPie to the same host are completely independent
However, HTTPie supports persistent sessions using the –session=SESSION_NAME_OR_PATH parameter. Custom headers (except those starting with Content- and If-), authorization, and cookies(specified manually or sent by the server) are persisted in a session with the same host
Create a new session
http --session=/tmp/session.json example.org API-Token:123
# Replication with existing session API-token is automatically set
http --session=/tmp/session.json example.org
Copy the code
All session data is stored as plain text, which means that session files can be manually added or modified using an editor — essentially JSON data
A named session
Each host can set up one or more sessions, for example: the following command will set up a session named name1 for requests whose host is example.org:
http --session=user1 -a user1:password example.org X-Foo:Bar
Copy the code
From now on, you select sessions by name, and when you select a session, the authorization and HTTP headers used before are automatically added:
http --session=user1 example.org
Copy the code
To create or reuse different sessions, just specify different names:
http --session=user2 -a user2:password example.org X-Bar:Foo
Copy the code
The named session will be stored in JSON data format under ~/.httpie/sessions/
/
. JSON (Windows: %APPDATA%\ Httpie \sessions\
\
. JSON)
Anonymous session
Instead of named sessions, you can use a file path directly to specify where the session files are stored, which can also reuse sessions between different hosts:
http --session=/tmp/session.json example.org
http --session=/tmp/session.json admin.example.org
http --session=~/.httpie/sessions/another.example.org/test.json example.org
http --session-read-only=/tmp/session.json example.org
Copy the code
Read-only session
If you reuse a session without updating the session information, you can specify –session-read-only=SESSION_NAME_OR_PATH
configuration
HTTPie uses a simple JSON configuration file
Configuration file path
The default configuration file path is ~/.httpie/config.json (window is in %APPDATA%\httpie\config.json). The configuration file path can also be changed by modifying the environment variable HTTPIE_CONFIG_DIR. You can use the HTTP –debug command to view the current configuration file path
Configurable parameters
The JSON configuration file contains the following keys:
default_options
An array of default parameters (empty by default) that will be applied to each HTTPie call
For example, you can use this option to change the default styles and output parameters: “default_options”: [“–style=fruity”, “–body”], another common default argument is “–session=default”, which causes HTTPie to always use the session (named default). You can also change the default JSON type, which is not strictly strict, to form using –form
__meta__
HTTPie automatically stores some of its own metadata, leave it alone
Cancels the previously specified parameter
Parameters in the configuration file and any other methods that specify parameters can be cancelled using the — no-option argument, such as –no-style or –no-session
The script
The –check-status flag is useful when using HTTPie in shell scripts. This flag will tell HTTPie if the response status code is 3xx, 4xx, or 5xx the application will exit and display the corresponding error code 3 (unless –follow is specified), 4, 5
#! /bin/bash
ifHTTP --check-status --ignore-stdin --timeout=2.5 HEAD example.org/health &> /dev/null;then
echo 'OK! '
else
case $? in
2) echo 'Request timed out! ' ;;
3) echo 'Unexpected HTTP 3xx Redirection! ' ;;
4) echo 'HTTP 4xx Client Error! ' ;;
5) echo 'HTTP 5xx Server Error! ' ;;
6) echo 'Exceeded --max-redirects=
redirects! '
;;
*) echo 'Other Error! ' ;;
esac
fi
Copy the code
Best practices
You usually don’t want to use the default behavior of stdin in the case of non-interactive calls, and you can disable it with the –ignore-stdin argument
Without this option, HTTPie may hang, which is a common problem. A scenario could occur where, for example, stdin is not connected to a terminal when HTTPie is called from a scheduled task. Therefore, the rule for redirecting input applies, i.e. HTTPie starts reading it in the hope that the request body will be delivered. With no data and no EOF, it gets stuck. Therefore, use this flag in your script unless you are passing some data to HTTPie
Of course it’s a good idea to manually set the delay using the –timeout parameter (30 seconds by default)
Meta information
Interface design
The design of command-line arguments is closely related to the process of sending HTTP requests over the network. This makes HTTPie’s commands easier to remember and read. Sometimes you can even concatenate native HTTP requests on a single line to form a natural HTTPie command line argument. For example, compare the following native HTTP request:
POST/Collection HTTP/1.1 X-API-key: 123 user-agent: Bacon/1.0 content-type: application/x-www-form-urlencoded name=value&name2=value2Copy the code
Send the same arguments as HTTPie:
http -fPOST example.org/collection \ x-api-key :123 \ user-agent :Bacon/1.0 \ name=value \ name2=value2Copy the code
Note that the order and arguments are very similar in both cases, and only a small number of commands are used to control HTTPie (-f means to send an HTTPie from request), and do not directly correspond to any part of the request
The two modes –pretty=all (the default on the command line) and –pretty= None (the default on redirected output) are friendly for interactive use and script calls, with HTTPie serving as a generic HTTP client in this process
As HTTPie is still under frequent development, some of the existing command line arguments may be tweaked slightly before the final 1.0 release. These adjustments are recorded in the change log
User support
There are some ways you can find support
- GitHub issues
- Our Gitter chat room
- StackOverflow
- @clihttp or @jkbrzt
Related projects
Rely on
The HTTPie base uses two particularly cool libraries:
Requests — Python HTTP library Pyanswers — Python code highlighted
HTTPie friend
HTTPie can happily play with the following two friends:
jq http-prompt
contribution
CONTRIBUTING.rst
Change log
CHANGELOG
illustrations
claudiatd/httpie-artwork
license
BSD-3-Clause: LICENSE
The author
Jakub Roztocil (@jkbrzt) created HTTPie, and some good people contributed as well