13 stable releases

2.0.0 Apr 17, 2024
1.6.1 Apr 7, 2023
1.6.0 Jan 21, 2022
1.5.2 Sep 2, 2021
0.1.8 Jul 7, 2020

#105 in #response


Used in 2 crates

MIT license

135KB
3.5K SLoC

:imagesdir: doc ifdef::env-github[] :imagesdir: https://raw.githubusercontent.com/Leopard2A5/fhttp/master/doc endif::[]

:toc:

link

What's this?

The file-based command line http client.

FHTTP is not a curl replacement. It’s meant to be a developers’ tool to make http requests and store them as files, usually in a source code repository along with an application accepting http requests. It’s inspired by tools like Postman, Insomnia and the IntelliJ http client.

|=== |Feature |CUrl |FHTTP |Postman |Insomnia |Intellij

|GUI |✕ |✕ |✓ |✓ |✕ |Request collections |✕* |✓ |✓ |✓ |✓ |Versioning |✕* |✓ |✕ |✕ |✓ |Scriptable |✓ |✓ |✕ |✕ |✕ |Env vars |✓ |✓ |✕ |✕ |✓ |Profiles |✕ |✓ |✓ |✓ |✕ |Pass secrets |✕* |✓ |✕ |✕ |✕ |Run multiple requests in one operation |✕ |✓ |✓ |✕ |✕ |Share collections |✕* |✓ |✓** |✕ |✓ |Full JavaScript response processing |✕ |✕ |✓ |✕ |✓ |Plugins |✕ |✕ |✕ |✓ |✕ |GraphQL schema autocompletion |✕ |✕ |✕ |✓ |✕

|=== $$*$$ available if you use CUrl with shell scripts

$$**$$ requires account

Installation

There are multiple ways to install FHTTP:

  • homebrew . run brew tap Leopard2A5/fhttp && brew install fhttp
  • through cargo . run cargo install fhttp (note: on ubuntu you need the apt packages build-essential, pkg-config and libssl-dev)
  • manually . download the latest version here . rename the downloaded file? . make the file executable . make sure it’s on your PATH

Linux users: if you get

error while loading shared libraries: libssl.so.1.0.0: cannot open shared object file: No such file or directory

you need to install libssl1.0.0: sudo apt-get install libssl1.0.0


Features

  • Simply author a request in a *.http file
  • Save a collection of requests right in your project repository
  • Use profiles to easily switch between environments
  • Resolve (environment) variables in your requests
  • Resolve secrets stored in pass
  • Add dependencies between requests
  • Support for graphql requests
  • multipart file uploads
  • export to cURL command

Anatomy of a request file

HTTP format

A request file looks like this: [source]

METHOD URL
HEADERS?

BODY?

RESPONSE_HANDLER?

The only mandatory parts are the method (get, post, patch, ...) and the url. You can prefix header lines with # to ignore that line.

Example request: [source]

POST https://oauth2tokenendpoint
content-type: application/json; charset=UTF-8

{
    "client_id": "foo",
    "client_secret": "bar"
}

> {%
    json $.access_token
%}

JSON and YAML

Since version 1.6, FHTTP supports requests in json and yaml file formats. The main advantage of these formats is that they are well-known and that they allow you to create multipart requests with greater control. They are also the only way in FHTTP to mix file parts and form-data parts in a multipart request. The format and structure of the formats is the same.

YAML format is recommended because of JSON's verbosity and YAML's improved multiline string handling features.

.Graphql request

method: post
url: http://localhost/graphql
headers:
  authorization: Bearer ${request("token.http")}
  content-type: application/json
body: |
  {
    "query": "query($series: String!) { characters(series: $series) { name } }",
    "variables": {
      "series": "Breaking Bad"
    }
  }
response_handler:
  json: "$.data.characters"

.Multipart json request

{
    "method": "post",
    "url": "http://localhost/upload",
    "body": [
        {
            "name": "metadata",
            "text": "{ \"foo\": \"bar\" }",
            "mime": "application/json"
        },
        {
            "name": "file",
            "filepath": "image.png"
        }
    ]
}

As with *.http files, method and url are mandatory, while headers, body and response_handler are optional fields.

Note that json and yaml formats don't have a graphQL convenience function as *.gql.http requests do.

The body atttribute can either be a plain string or a list of objects to create a multipart request. Each object needs a name and either a text or filepath. Optionally you can force a content-type for that part via the mime attribute.

Output

FHTTP conveniently prints log messages to stderr and response bodies to stdout. For example:

> fhttp get-entities.http

[source]

> fhttp request.http
POST https://auth-server/token... 200 OK
GET https://server/entities... 200 OK
{
    "payload": 123
}

In this example get-entities.http has a dependency on another request to fetch an authentication token, which is executed first. FHTTP then preprocesses get-entities.http with the data from token.http and executes it, printing the result to stdout.

You can tell FHTTP to print the paths to the executed request files instead of methods and urls, by passing the -P or --print-paths flag. This is particularly useful when working with graphql servers that combine several queries and mutations under a single path (/graphql).

Verbose option

By increasing the verbosity with the -v option, you can tell FHTTP to also log usage of pass secrets. This can be useful if FHTTP seems slow, because the pass lookup can take some time.

How does it work?

When you invoke FHTTP, the following will happen:

  1. find profile file, load default profile, load requested profile, if any
  2. for every given request, find referenced requests, find best execution order
  3. for every request . resolve variables . insert dependency results . send request . apply response handler, if any . save result . print result, unless this request is a dependency and the user didn't explicitly specify it when invoking FHTTP

Request preprocessing

You can use expressions in your request files. Expressions have the form ${expression}. The following table gives an overview of what's currently supported.

.Preprocessing expressions |=== | Expression | Description | Usable in

| ${env(NAME)} | Insert the environment variable NAME, or a profile variable with that name. If the variable is not found, FHTTP will prompt you for it, unless you've activated the --no-prompt option. | method, url, headers, body

| ${env(NAME, "default")} | Insert the environment variable NAME, or the given default value if the environment variable is not set. | method, url, headers, body

| ${randomInt(lower, upper)} | Insert a random integer. Lower and upper bounds are optional; you have to give a lower if you want to give an upper bound. | method, url, headers, body

| ${uuid()} | Insert a randomly generated UUID. | method, url, headers, body

| ${request("PATH")} | Insert the postprocessed body of the request file denoted by PATH. PATH can be absolute or relative to the location of the file containing the request(...) expression. | method, url, headers, body

| ${include("PATH")} | Insert the content of the file denoted by PATH. FHTTP will remove a single trailing newline character when including a file.

You can use all expressions inside included files, including include itself, this is especially useful when working with GraphQL fragments. | method, url, headers, body

| ${include_indent("PATH")} | like include, but preserve the indentation of the point of invocation in the included text. Particularly useful in yaml requests, where the normal include may invalidate the yaml document. | see ${include("PATH")}

| ${file("NAME", "PATH")} | Only supported in the body segment of a request. replaces all other body content except for other file(...) expressions. Use this to send a multipart request, uploading the given file(s). | body |===

Response handlers / postprocessing

Every request can contain a single response handler expression. To specify a response handler, leave an empty line after the body, then put the expression in > {% handler %}. For example:

[source]

POST http://localhost:8080

{
    "foo": "bar"
}

> {%
    json $.path.inside.response
%}

.Supported response handlers |=== | Handler | Description

| json | Accepts a jsonpath expression that is applied to the response body. | deno | *** Deno is no longer supported. *** |===

Profiles

You can create profiles to avoid having to provide variables manually every time you invoke FHTTP. Profiles allow you to easily switch the target environment of a request. By default, FHTTP will use a file called fhttp-config.json if present. A profile file could look like this:

[source,json]

{
    "default": {
        "variables": {
            "URL": "http://localhost:8080"
        }
    },
    "localhost": {
        "variables": {
            "token": "NO_AUTH"
        }
    },
    "testing": {
        "variables": {
            "URL": "https://testing.myapp.com",
            "CLIENT_ID": "clientid",
            "CLIENT_SECRET": {
                "pass": "path/to/clientsecret/in/passwordstore"
            },
            "token": {
                "request": "get_token.http"
            }
        }
    }
}

You can change which profile file to use by using the --profile-file option.

You can specify which profile to use with the --profile option. The default profile is always loaded if one is present and its values are overwritten by any other profile you specify.

Variables in profiles can have different forms:

.Profile variables |=== | Variable | Description | Example

| String | Sets the variable to this string. a| [source]

"var": "string"

| Pass secret | Resolves the variable using the pass password store. a|[source,json]

{
    "pass": "path/in/pass"
}

| Request | Resolve a request and use the postprocessed response body for the variable. Absolute path or relative from the location of the profile file. a| [source,json]

{
    "request": "path/to/request/file"
}

|===

Graphql

GraphQL requests are transmitted to the server as json, so naively a graphql request file would look like this:

[source]

POST http://graphqlserver
Content-Type: application/json

{
  "query": "query($var1: String!) { foo(var1: $var1) { field1 } }",
  "variables": {
    "var1": "val1"
  }
}

That's not very pretty, especially with longer graphql queries, as we need to escape line breaks in json. However, FHTTP supports graphql requests directly. Just change the file's extension to *.gql.http or *.graphql.http and change it like this:

[source]

POST http://graphqlserver

query($var1: String!) {
  foo(var1: $var1) {
    field1
  }
}

{
  "var1": "val1"
}

FHTTP automatically sets the content-type to application/json, escapes the query string and constructs the json payload with the query and variables. Response handlers are also supported in graphql requests. Graphql requests also support the full range of preprocessing expressions.

Command line flags and options

.Command line flags |=== | Short | Long | Description

| -h | --help | Print the help screen.

| | --no-prompt | Fail on missing environment variables instead of prompting for input.

| -P | --print-paths | Print request file paths instead of method and url.

| -c | --curl | Print cURL commands instead of executing requests. Still executes dependencies, only requests listed on the command line are exported as cURL commands. Secrets will be exported as evaluations, e.g. $(pass secretpath).

| -q | --quiet | Suppress log outputs.

| -v | --verbose | Control log verbosity.

| -V | --version | Print the application's version.

|===

.Command line options |=== | Short | Long | Description

| -p | --profile | The name of the profile to use.

Defaults to "default".

Can be overwritten by env var FHTTP_PROFILE.

| -f | --profile-file | Path of the profile file to use.

Defaults to fhttp-config.json.

Can be overwritten by env var FHTTP_PROFILE_FILE.

| -t | --timeout-ms | Set a timeout in ms per request.

| -o | --out | Path to write stdout output to.

Will create set file or overwrite contents of existing file.

|===

Dependencies

~16–31MB
~497K SLoC