winzik/docs/ide/http-client.md

147 lines
9.1 KiB
Markdown

# HTTP client
The **HTTP Client** window (bottom tool bar, globe icon) writes and sends the requests of your API: collections, environments,
authentication, scripts and tests, history. The **OpenAPI** window (right) shows the API description of the project and opens any
operation in the HTTP Client.
![The HTTP Client: a collection, a request with its script, the answer](images/http-client-request.png)
## Collections and files
Everything is plain text in the project, committed and reviewed like code:
```
http-requests/<collection>/collection.json name, auth, headers, sharing
http-requests/<collection>/http-client.env.json the environments
http-requests/<collection>/<folder>/<request>.http
```
**New Request** makes a request in the collection; the folder button opens a collection. **Ctrl+Enter** sends, **Ctrl+S** saves.
The **History** tab keeps what was sent.
A request file is the `.http` format that other editors read (request line, headers, blank line, body), with the IDE's own settings
in `# @` comments that those editors skip:
```http
# @name Create a book
# @seq 2
# @auth jwt login=auth/login.http path=$.token var=token
# @no-redirect
# @insecure
# @timeout 30
POST {{baseUrl}}/api/books
Content-Type: application/ld+json
{"title": "Dune"}
> {%
client.test("created", () => client.assert(response.status === 201));
client.global.set("bookId", response.body.id);
%}
```
`# @name` and `# @seq` (order), `# @no-redirect`, `# @insecure` (accept a self-signed certificate) and `# @timeout` are per request.
A script between `< {% … %}` runs before the request, one after `> {% … %}` runs after the answer.
## Environments and variables
**Environments…** (the toolbar) edits the environments of a collection (`local`, `prod`…); the *Library* selector chooses the one in
use.
![The Environments dialog: a secret value is kept on this computer](images/http-client-environments.png)
- `{{name}}` is replaced by an environment variable, a value set by a script or a login, or a `@name = value` line of the file.
- Dynamic values: `{{$uuid}}`, `{{$timestamp}}`, `{{$isoTimestamp}}`, `{{$randomInt}}`, `{{$random.integer(1, 10)}}`,
`{{$random.alphanumeric(8)}}`, `{{$random.email}}`.
- **Secrets**: tick *Secret* on a variable. Its value, the tokens and the values set by scripts are kept **on this computer only**
(`~/.jumphp/ide-http-secrets.json`, readable by you alone): never in the project, never sent to jumphp.net, masked in the history.
## Authentication
Set on the collection (**Collection Settings…**), inherited by its requests, or chosen per request in the *Auth* tab (`# @auth`):
- none, **bearer**, **basic**, **API key** (header or query);
- **JWT**: a *login request* of the collection is sent, the token is read from its answer with a JSONPath and kept in a variable
(`{{token}}`). The login is sent when there is no token, when it expires in less than 30 seconds, or once more when the API
answers 401;
- **OAuth2**: *client credentials* or *password* grant, the token kept until `expires_in`.
**Forget the Tokens and Script Values** in the Auth tab starts again from nothing.
## Scripts and tests
Scripts run in a Web Worker without network access, and stop after 3 seconds. Available: `client.global.set / get`,
`client.test(name, fn)`, `client.assert(cond, message)`, `request.variables.set`, `req.setHeader / setBody / setUrl` (before the
request), `response.status / body / headers / responseTime`, `expect(x).to.equal / eql / have.property / include / match / above /
below / lengthOf`, `.not`, `jsonpath(data, path)` and `console.log`. Bruno's `bru`, `res`, `req` and `test()` work too. **Snippets**
inserts common ones; the *Tests* tab of the answer lists the results (`2/2 tests`).
## The answer
The IDE itself sends the request (HTTP/1.1, gzip, chunked, cookies kept per site until the IDE closes). It shows the status, the time
(connect / TLS / wait / download), the size, headers, cookies, the test results and the body: *Pretty* (JSON, XML, HTML), *Raw*, a
*Table* (a JSON array, an API Platform `member`), an HTML preview (sandboxed) or the picture. A JSONPath filter narrows the body,
**Ctrl+F** searches it, **Copy as curl** copies the command. The *Timeline* shows the chain of redirects. The only thing sent about
you is `User-Agent: jumphp-ide`, unless the request sets one.
**Preview** draws an HTML answer as the site would: the IDE fetches its stylesheets (and their `@import`, fonts and `url()` pictures),
`<img>` / `srcset` pictures, inline-style pictures and icons, relative to the response's address, with the request's own TLS
setting and cookies, and puts them inside the page. Only the page's own host (and its sibling subdomains, or localhost for a local
page) is ever contacted, at most 8 MB a resource; other hosts, private addresses and redirects out of the site are refused.
The note beside **Reload resources** lists what could not be loaded (hover it). The frame stays sandboxed; **Scripts** (off by
default) runs the page's own scripts.
## Refresh from the API
The blue **Refresh from the API (OpenAPI / API Platform)** button of the toolbar pulls everything the project says about its API into
**one organised collection**, `API`: a folder per resource (API Platform's short name, or the OpenAPI tag), one request per
operation inside it, sorted (list, get, create, replace, update, delete, then the custom operations), the JWT login in `auth/` when
`lexik/jwt-authentication-bundle` is installed (the collection's authentication), and an environment whose `{{baseUrl}}` is the
address of the local site (see OpenAPI below).
- With **API Platform** the requests are made from the code (the API Platform window's generator: example bodies from the writable
properties, the filters as query parameters). Otherwise they come from the OpenAPI description: the running site's, or the project
file (`var/openapi.json` after *Regenerate the schema*).
- Running it again is safe: a request you **edited** is never overwritten (the new version is written beside it as `*.theirs.http`),
untouched requests follow the code, new operations are added, and untouched requests of operations that disappeared are deleted.
A summary says how many were added, updated, kept, removed and unchanged. What the tool wrote is remembered by hash in
`.apiplatform.json` of the collection.
## OpenAPI
![The OpenAPI window: operations, schemas, examples](images/http-client-openapi.png)
The description comes from a file of the project (`openapi.yaml|json`, `swagger.*`) or from an address: API Platform's
`/api/docs.jsonopenapi`, `/api/docs.json`, NelmioApiDocBundle's `/api/doc.json`, on the address of the project's **local site**: the
port of `bin/jumphp web:serve` (the "Serve the site" run configuration, also for symfony-docker), the published port of the PHP / web
service of your own compose file, else `DEFAULT_URI` / `APP_URL` of `.env` (a bare `http://localhost` is only Symfony's placeholder: it
comes last). The window asks each candidate address and keeps the one that answers. OpenAPI 3.x and Swagger 2.0, JSON or YAML; `$ref` are resolved, `allOf` merged,
and an example is made from each schema.
- The line under the address shows the **local site** (its address, running or not). When it is not running, **Start the site** runs
the "Serve the site" run configuration, and the description is loaded by itself as soon as the site answers.
- **Regenerate the schema** (API Platform, NelmioApiDocBundle) runs the project's own console, through the Console window's runner
(Docker or the computer's PHP): `api:openapi:export --output=<file>` or `nelmio:apidoc:dump --format=json`, writes the file
(`var/openapi.json` by default, or the project file typed beside the button, remembered) and loads it: the schema is there even
when the site is stopped. **Reload** asks the site again.
- **Search the operations** filters the list; each shows its parameters, request body, answers and examples.
- **Try it** opens the operation in the HTTP Client, already filled: path parameters, required query parameters, Accept and
Content-Type, an example body, and the authentication of its security scheme (the collection's, when it is bearer, JWT or OAuth2).
- **Add All to the Collection** writes a request file for each operation, one folder per tag.
- *Accept a self-signed certificate* is for a local site.
## Import, export, sharing
- **Import**: `.http` files (several requests separated by `###`), Bruno `.bru` files and folders (with their environments), or
pasted text. **Export** a request, a folder or a collection as `.http` or `.bru`.
- **Share with the Project's Members…** then **Sync Now**: the files go to the jumphp.net project; members read them, the owner and
the members with write access change them. A change on one side goes to the other; a file changed on both sides keeps this
computer's version and writes the other one beside it as `<name>.theirs.http` (never shared). Environments travel **without their
secret values**.
## Limits
- Scripts have no network and a 3-second limit.
- Requests are sent in HTTP/1.1.
- Cookies are kept until the IDE closes.
- Secrets stay on one computer: each teammate fills them in.