# Copy as code

> Copy any captured request as cURL, Python, JavaScript, Swift, Go, a k6 load test, a Playwright test and more, or as a Markdown summary, ready to run or share.

Source: https://docs.subcloak.com/cloak-proxy/inspect/copy-as-code/

Copy as code turns a captured request into a command or code snippet that sends the same request: same method, URL, headers and body. Use it to reproduce a bug from the terminal, hand a failing call to a teammate, or start a script from what your app really sent. There are 24 formats: cURL, 21 other languages, libraries and test tools, a Markdown summary, and a `.http` file.

## Copy a request as code

There are four ways, depending on where you are.

  **Right-click**

    1. Right-click a request in the [traffic list](https://docs.subcloak.com/cloak-proxy/inspect/traffic-list/).
    2. Choose **Copy as cURL**, or choose **Copy as ›** and pick a format.

    With several requests selected, you get one snippet per request, separated by a blank line.

  **Code tab**

    1. Select a request and open the **Code** tab in the request pane.
    2. Choose a format from the menu.

       The code appears below, so you can read it before copying.

    3. Click the copy button at the right of the format menu.

    The tab remembers the format you chose.

  **Inspector menu**

    1. Select a request.
    2. Click the ••• menu at the right of the inspector's summary bar and choose **Copy as cURL**.

  **Search Everything**

    1. Select one or more requests.
    2. Press <kbd>⇧</kbd> <kbd>⌘</kbd> <kbd>A</kbd> and type `copy as` and a format, for example `copy as go`.
    3. Press <kbd>Return</kbd>.

*[Screenshot: The Code tab with cURL selected, showing a line-numbered curl command with the URL and Authorization, Accept and Cookie headers, and a copy button. The Code tab shows the snippet before you copy it.]*

Encrypted tunnels have no request to copy and are skipped.

A request paused at a breakpoint has its own **Copy** menu, which copies it with your edits. See [Copy the paused request](https://docs.subcloak.com/cloak-proxy/tools/breakpoint/#copy-the-paused-request).

## Formats

| Menu name | Produces |
|---|---|
| **cURL** | A `curl` command, one option per line |
| **Swift** | `URLRequest` and `URLSession.shared.data(for:)` with `async`/`await` |
| **JavaScript** | `fetch` with `await`. JSON bodies are passed through `JSON.stringify`. |
| **Python** | The `requests` library. JSON bodies become a Python dictionary passed as `json=`. |
| **Go** | `net/http` with `http.NewRequest` |
| **HTTPie** | An `http` command. A body is piped in with `echo`. |
| **Shell – wget** | A `wget` command that prints the response |
| **HTTP** | The raw HTTP/1.1 request, with `Host` and `Content-Length` |
| **NodeJS – Axios** | `axios.request` |
| **Python – http.client** | The standard library's `http.client` |
| **Java – OkHttp** | OkHttp's `Request.Builder` |
| **Kotlin – OkHttp** | OkHttp with Kotlin extensions (`toMediaType`, `toRequestBody`) |
| **C# – HttpClient** | `HttpClient` and `HttpRequestMessage` |
| **PHP – cURL** | `curl_setopt_array` |
| **Ruby – Net::HTTP** | `Net::HTTP`, with `use_ssl` for HTTPS |
| **Rust – reqwest** | `reqwest::Client` in a `tokio` main function |
| **Dart – http** | The `http` package's `http.Request` |
| **PowerShell** | `Invoke-RestMethod` with a headers dictionary |
| **C – libcurl** | A small C program using `curl_easy` |
| **k6 – load test** (added in Cloak Proxy 0.2.0) | A k6 script that sends the request with 10 virtual users for 30 seconds (`options = { vus: 10, duration: '30s' }`), checks for a 2xx status and sleeps a second between iterations. Run it with `k6 run`. |
| **Python – httpx** (added in Cloak Proxy 0.2.0) | The `httpx` library. JSON bodies become a Python dictionary passed as `json=`; other text bodies go in `content=`. |
| **Playwright – API test** (added in Cloak Proxy 0.2.0) | A `@playwright/test` test named after the method and path that sends the request with `request.fetch` and expects `response.ok()`. JSON bodies go in `data`. |
| **Markdown** | A heading with the method and URL, a table of headers and the body in a code block. For bug reports and docs, not for running. |
| **.http (REST Client)** | A `.http` request for VS Code's REST Client, JetBrains HTTP Client or Cloak Proxy's own `.http` files: a `###` title, the request line, the headers (without `Host` and `Content-Length`) and the body, decompressed. |

The language snippets print the response when they run; most print the status code and the body. The k6 and Playwright snippets check the status instead.

## Example

A `POST` to `https://api.example.com/v1/orders` with a JSON body and a bearer token comes out like this:

  **cURL**

    ```bash title="Terminal"
    curl \
      -X POST \
      'https://api.example.com/v1/orders' \
      -H 'Content-Type: application/json' \
      -H 'Authorization: Bearer sk_test_xxxx' \
      --data-binary '{"sku":"A1","qty":2}'
    ```

  **Python**

    ```python title="orders.py"
    import requests

    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer sk_test_xxxx",
    }
    payload = {
        "sku": "A1",
        "qty": 2
    }
    response = requests.request("POST", "https://api.example.com/v1/orders", headers=headers, json=payload)
    print(response.status_code, response.text)
    ```

  **JavaScript**

    ```js title="orders.mjs"
    const response = await fetch("https://api.example.com/v1/orders", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": "Bearer sk_test_xxxx"
      },
      body: JSON.stringify({"sku":"A1","qty":2})
    });
    console.log(response.status, await response.text());
    ```

  **Swift**

    ```swift title="Orders.swift"
    import Foundation

    var request = URLRequest(url: URL(string: "https://api.example.com/v1/orders")!)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("Bearer sk_test_xxxx", forHTTPHeaderField: "Authorization")
    request.httpBody = Data("""
    {"sku":"A1","qty":2}
    """.utf8)

    let (data, response) = try await URLSession.shared.data(for: request)
    print((response as? HTTPURLResponse)?.statusCode ?? 0)
    print(String(decoding: data, as: UTF8.self))
    ```

  **k6**

    ```js title="orders-load.js"
    import http from 'k6/http';
    import { check, sleep } from 'k6';

    export const options = { vus: 10, duration: '30s' };

    export default function () {
      const headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer sk_test_xxxx",
      };
      const res = http.request("POST", "https://api.example.com/v1/orders", "{\"sku\":\"A1\",\"qty\":2}", { headers });
      check(res, { 'status is 2xx': (r) => r.status >= 200 && r.status < 300 });
      sleep(1);
    }
    ```

  **Markdown**

    ````markdown title="Bug report"
    ### POST https://api.example.com/v1/orders

    **Headers**

    | Name | Value |
    |---|---|
    | Host | api.example.com |
    | Content-Type | application/json |
    | Authorization | Bearer sk_test_xxxx |
    | Content-Length | 20 |

    **Body**

    ```
    {
      "sku": "A1",
      "qty": 2
    }
    ```
    ````

## What's included and what's left out

| | cURL | Markdown | Every other format |
|---|---|---|---|
| Method and URL | Yes. `-X` is added unless it's a `GET` without a body. | Yes, in the heading | Yes |
| Headers | All except `Content-Length`, `Connection` and `Proxy-Connection`. `Host` only when it differs from the URL's host. `--compressed` is added when the request has `Accept-Encoding`. | All, in a table | All except `Host`, `Content-Length`, `Connection`, `Proxy-Connection` and `Accept-Encoding` |
| Text body | As `--data-raw '…'`, so a body that starts with `@` is never read as a file | In a code block, indented if it's JSON | In the language's own form |
| Binary body | Printed by `printf` and piped in with `--data-binary @-`, so the command needs no extra file | Left out | Left out |
| Compressed request body | The captured bytes, piped in like a binary body | Decompressed | Decompressed. The `Content-Encoding` header is still included, so remove it before running. |

> **Snippets contain secrets:**
> Copied code includes every header the app sent, including `Authorization`, cookies and API keys, exactly as captured. Copy as code doesn't redact anything. Remove secrets before pasting a snippet into a ticket, chat or document, or share an [export with redaction](https://docs.subcloak.com/cloak-proxy/sessions/redaction/) instead.

## Run a copied request through Cloak Proxy

A copied snippet talks to the server directly, so its traffic doesn't appear in Cloak Proxy unless the program uses the proxy. To see it, run it from a terminal that's set up for Cloak Proxy (see [Terminal and runtimes](https://docs.subcloak.com/cloak-proxy/devices/terminal-and-runtimes/)), or resend the request from inside the app with [Repeat or Edit and Repeat](https://docs.subcloak.com/cloak-proxy/tools/repeat-and-compose/).

To keep a request and work on it, save it to the [API client](https://docs.subcloak.com/cloak-proxy/api-client/capture-to-client/), which has its own [code snippets](https://docs.subcloak.com/cloak-proxy/api-client/code-snippets/).

To get type definitions for a JSON response or request body instead of code that sends the request, right-click the request and choose **Generate Types from Response…** or **Generate Types from Request Body…**. See [Generate types](https://docs.subcloak.com/cloak-proxy/inspect/generate-types/).

## Related

  - [Repeat and Compose](https://docs.subcloak.com/cloak-proxy/tools/repeat-and-compose/): Resend a request, or change it first.
  - [Export](https://docs.subcloak.com/cloak-proxy/sessions/export/): Save requests as HAR, CSV, Postman or OpenAPI.
  - [Capture to the API client](https://docs.subcloak.com/cloak-proxy/api-client/capture-to-client/): Turn captured requests into saved, editable ones.
  - [Terminal and runtimes](https://docs.subcloak.com/cloak-proxy/devices/terminal-and-runtimes/): Point curl, Node and Python at Cloak Proxy.
