fhttp-core 2.1.0

core library for the fhttp tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
:imagesdir: doc
ifdef::env-github[]
:imagesdir: https://raw.githubusercontent.com/Leopard2A5/fhttp/master/doc
endif::[]

:toc:

image::logo.png[]
image:https://github.com/Leopard2A5/fhttp/workflows/.github/workflows/test.yml/badge.svg[]
image:https://img.shields.io/twitter/follow/fhttp_tool?style=social[link=https://twitter.com/fhttp_tool]

== 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                                       |✕   |✓   |✓   |✓   |✕
|https://www.passwordstore.org/[Pass] secrets   |✕*  |✓   |✕   |✕   |✕
|https://1password.com/[1Password] 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:

* through cargo (recommended, currently the only way to install for apple silicon)
. run `cargo install fhttp` (note: on ubuntu you need the apt packages `build-essential`, `pkg-config` and `libssl-dev`)
* homebrew
. run `brew tap Leopard2A5/fhttp && brew install fhttp`
* manually
. download the latest version https://github.com/Leopard2A5/fhttp/releases[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 https://www.passwordstore.org/[pass] or https://1password.com/[1Password]
* 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
```yaml
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
```json
{
    "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 secrets. This can be useful if FHTTP seems slow, because the secret lookup can take some time.

== How does it work?

image::process.png[]

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 https://support.smartbear.com/readyapi/docs/testing/jsonpath-reference.html[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 https://www.passwordstore.org/[pass] password store.
a|[source,json]
----
{
    "pass": "path/in/pass"
}
----

| 1Password secret
| Resolves the variable using the https://1password.com/[1Password] password store (requires the https://developer.1password.com/docs/cli/[CLI binary]). FHTTP will call `op read {path}`, so have a look at the 1Password documentation about the `op read` command.
a|[source,json]
----
{
    "onepassword": "op://path/in/store"
}
----

| 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.

|===