HTTPSnippet

repository·master·Indexed 22 days ago

https://github.com/kong/httpsnippet

An HTTP request snippet generator that converts HAR (HTTP Archive) data into executable code across a wide variety of programming languages and libraries. It provides a CLI and a TypeScript library for programmatic use, allowing users to specify targets (languages) and clients (libraries) to generate the desired code snippets.

Tokens
14K
Snippets
31
Records
99
Agent score
74%

What's inside httpsnippet

  1. How HTTPSnippet works: Targets, Clients, and Options

    master

    HTTPSnippet converts HTTP requests in HAR (HTTP Archive) format into executable code for various languages and tools. The conversion process is governed by three concepts:

    1. Target: A group of code generators, typically representing a programming language (e.g., Rust, Go, C, OCaml).
    2. Client: A specific generator within a target, referring to a particular library (e.g., the C# target has httpclient and restsharp clients).
    3. Options: Per-client configuration settings used to control formatting, such as indentation behavior.

    Input is a JSON object representing a HAR request or a full HAR log.

  2. Understand the Request object structure

    master

    When you initialize HTTPSnippet, it processes raw HAR data into an enriched Request object. This object contains the original HAR data plus several helper objects to make snippet generation easier.

    Key Properties

    • fullUrl: The complete URL including the query string.
    • url: The base URL without the query string.
    • uriObj: A parsed URL object containing pathname, query, search, and path.
    • headersObj: An object containing all request headers (keys are normalized based on the HTTP version).
    • queryObj: An object containing the parsed query string parameters.
    • cookiesObj: An object containing the request cookies.
    • allHeaders: A merged object containing both standard headers and the cookie header string.
    • postData: The request body, which includes jsonObj (for JSON requests) or paramsObj (for form-encoded requests).
  3. Convert HAR requests using the HTTPSnippet class

    master

    Initialize a new HTTPSnippet instance with a HarRequest or HarEntry object, then call .convert() to generate the code.

    Method Signature: snippet.convert(targetId: string, clientId?: string, options?: T): string

    • targetId: The ID of the target (e.g., 'node', 'shell', 'go').
    • clientId (Optional): The specific client within the target. If omitted, the target's default client is used.
    • options (Optional): An object containing client-specific configuration (e.g., { indent: '\t' }).
    import { HTTPSnippet } from 'httpsnippet';
    
    const snippet = new HTTPSnippet({
      method: 'GET',
      url: 'http://mockbin.com/request',
    });
    
    // Generate default client for 'node'
    console.log(snippet.convert('node'));
    
    // Generate 'node' with specific indentation
    console.log(
      snippet.convert('node', undefined, {
        indent: '\t',
      }),
    );
  4. Extend HTTPSnippet with custom targets and clients

    master

    You can add your own custom generators to HTTPSnippet using addTarget and addTargetClient.

    • addTarget(target: Target): Adds a completely new target.
    • addTargetClient(targetId: TargetId, client: Client): Adds a new client to an existing target.
    • isTarget(target: any): Type guard to validate if an object is a valid Target.
    • isClient(client: any): Type guard to validate if an object is a valid Client.
    import { HTTPSnippet, addTargetClient, isTarget, isClient } from 'httpsnippet';
    
    // Adding a custom client to an existing target
    addTargetClient('customTargetId', myCustomClient);
    
    const snippet = new HTTPSnippet(HAR);
    const output = snippet.convert('customTargetId', 'customClientId');
    
    // Validation
    try {
      console.log(isTarget(myCustomTarget));
    } catch (error) {
      console.error(error);
    }
  5. Configure Ruby native client options

    master

    The RubyNativeOptions interface allows you to control SSL behavior in the generated Ruby code.

    OptionTypeDefaultDescription
    insecureSkipVerifybooleanfalseIf true, the generated code sets http.verify_mode = OpenSSL::SSL::VERIFY_NONE to skip SSL certificate verification for HTTPS requests.
    export interface RubyNativeOptions {
      insecureSkipVerify?: boolean;
    }
  6. Configure Python 3 client options

    master

    When using the python3 client in httpsnippet, you can provide an optional Python3Options object to control SSL verification behavior.

    • insecureSkipVerify (boolean, optional): If set to true, the generated Python code will import the ssl module and use ssl._create_unverified_context() to bypass SSL certificate verification. Defaults to false.
  7. Configure PHP HTTP/2 snippet generation options

    master

    When using the http2 client to generate PHP code snippets, you can pass an Http2Options object to customize the output format.

    Supported options:

    • closingTag (boolean): If true, appends a PHP closing tag ?> to the end of the snippet.
    • noTags (boolean): If true, the generated code will not include PHP opening tags (<?php or <?).
    • shortTags (boolean): If true and noTags is false, uses the short opening tag <? instead of <?php.
    export interface Http2Options {
      closingTag?: boolean;
      noTags?: boolean;
      shortTags?: boolean;
    }
  8. Configure the R httr client options

    master

    When using the httr client for code generation, you can provide an options object to control the formatting of the output. Currently, the only available option is indent.

    OptionTypeDefaultDescription
    indentstring' 'The string used for indentation in the generated R code.
    export interface HttrOptions {
      /** @default '  ' */
      indent?: string;
    }
  9. Configure Crystal native client options

    master

    When using the Crystal native client target, you can pass the following options to customize the generated code:

    OptionTypeDefaultDescription
    insecureSkipVerifybooleanfalseIf true, the generated code will include , tls: OpenSSL::SSL::Context::Client.insecure to skip SSL certificate verification in the HTTP::Client call.
  10. Configure Guzzle PHP code generation options

    master

    When using the guzzle target to generate PHP code snippets, you can pass a GuzzleOptions object to customize the output format.

    Available options:

    • closingTag (boolean): If true, appends a PHP closing tag ?> to the snippet.
    • indent (string): The string used for indentation (e.g., ' ' or ' ').
    • noTags (boolean): If true, the snippet will not include the opening <?php or <? tag.
    • shortTags (boolean): If true and noTags is false, uses the short PHP opening tag <? instead of <?php.
    export interface GuzzleOptions {
      closingTag?: boolean;
      indent?: string;
      noTags?: boolean;
      shortTags?: boolean;
    }