• Stars
    star
    1,061
  • Rank 41,856 (Top 0.9 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

HTTP Request snippet generator for many languages & libraries

HTTPSnippet

version License

HTTP Request snippet generator for many languages & tools including: cURL, HTTPie, JavaScript, Node, C, Java, PHP, Objective-C, Swift, Python, Ruby, C#, Go, OCaml and more!

Relies on the popular HAR format to import data and describe HTTP calls.

See it in action on companion service: APIembed

Build Downloads

Quickstart

Core Concepts

  1. HTTPSnippet's input is a JSON object that represents an HTTP request in the HAR Request Object format.
  2. HTTPSnippet's output is executable code that sends the input HTTP request, in a wide variety of languages and libraries.
  3. You provide HTTPSnippet your desired target, client, and options.
    • a target refers to a group of code generators. Generally, a target is a programming language like Rust, Go, C, or OCaml.
    • client refers to a more specific generator within the parent target. For example, the C# target has two available clients, httpclient and restsharp, each referring to a popular C# library for making requests.
    • options are per client and generally control things like specific indent behaviors or other formatting rules.

CLI Quickstart

httpsnippet har.json \ # the path your input file (must be in HAR format)
  --target shell \ # your desired language
  --client curl \ # your desired language library
  --output ./examples \ # an output directory, otherwise will just output to Stdout
  --options '{ "indent": false }' # any client options as a JSON string

TypeScript Library Quickstart

import { HTTPSnippet } from 'httpsnippet';

const snippet = new HTTPSnippet({
  method: 'GET',
  url: 'http://mockbin.com/request',
});

const options = { indent: '\t' };
const output = snippet.convert('shell', 'curl', options);
console.log(output);

CLI Usage

CLI Installation

NPM Yarn
npm install --global httpsnippet
yarn global add httpsnippet
httpsnippet [harFilePath]

the default command

Options:
      --help     Show help                                   [boolean]
      --version  Show version number                         [boolean]
  -t, --target   target output                     [string] [required]
  -c, --client   language client                              [string]
  -o, --output   write output to directory                    [string]
  -x, --options  provide extra options for the target/client  [string]

Examples:
  httpsnippet my_har.json --target rust --client actix --output my_src_directory

Example

The input to HTTPSnippet is any valid HAR Request Object, or full HAR log format.

`example.json`
{
  "method": "POST",
  "url": "http://mockbin.com/har?key=value",
  "httpVersion": "HTTP/1.1",
  "queryString": [
    {
      "name": "foo",
      "value": "bar"
    },
    {
      "name": "foo",
      "value": "baz"
    },
    {
      "name": "baz",
      "value": "abc"
    }
  ],
  "headers": [
    {
      "name": "accept",
      "value": "application/json"
    },
    {
      "name": "content-type",
      "value": "application/x-www-form-urlencoded"
    }
  ],
  "cookies": [
    {
      "name": "foo",
      "value": "bar"
    },
    {
      "name": "bar",
      "value": "baz"
    }
  ],
  "postData": {
    "mimeType": "application/x-www-form-urlencoded",
    "params": [
      {
        "name": "foo",
        "value": "bar"
      }
    ]
  }
}
httpsnippet example.json --target shell --client curl --output ./examples
$ tree examples
examples/
└── example.sh

inside examples/example.sh you'll see the generated output:

curl --request POST \
  --url 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' \
  --header 'accept: application/json' \
  --header 'content-type: application/x-www-form-urlencoded' \
  --cookie 'foo=bar; bar=baz' \
  --data foo=bar

provide extra options:

httpsnippet example.json --target shell --client curl --output ./examples --options '{ "indent": false }'

and see how the output changes, in this case without indentation

curl --request POST --url 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' --header 'accept: application/json' --header 'content-type: application/x-www-form-urlencoded' --cookie 'foo=bar; bar=baz' --data foo=bar

TypeScript Library Usage

Library Installation

NPM Yarn
npm install --save httpsnippet
yarn add httpsnippet

Types

HarRequest

See https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/har-format for the TypeScript type corresponding to this type

HarEntry

interface Entry {
  request: Partial<HarRequest>;
}

interface HarEntry {
  log: {
    version: string;
    creator: {
      name: string;
      version: string;
    };
    entries: {
      request: Partial<HarRequest>;
    }[];
  };
}

TargetId

type TargetId = string;

ClientId

type ClientId = string;

Converter

type Converter<T extends Record<string, any>> = (
  request: Request,
  options?: Merge<CodeBuilderOptions, T>,
) => string;

Client

interface Client<T extends Record<string, any> = Record<string, any>> {
  info: ClientInfo;
  convert: Converter<T>;
}

Extension

type Extension = `.${string}` | null;

TargetInfo

interface TargetInfo {
  key: TargetId;
  title: string;
  extname: Extension;
  default: string;
}

Target

interface Target {
  info: TargetInfo;
  clientsById: Record<ClientId, Client>;
}

Library Exports

new HTTPSnippet(source: HarRequest | HarEntry)

Name of conversion target

import { HTTPSnippet } from 'httpsnippet';

const snippet = new HTTPSnippet({
  method: 'GET',
  url: 'http://mockbin.com/request',
});

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

The convert method requires a target ID such as node, shell, go, etc. If no client ID is provided, the default client for that target will be used.

Note: to see the default targets for a given client, see target.info.default. For example shell's target has the default of curl.

Many targets provide specific options. Look at the TypeScript types for the target you are interested in to see what options it provides. For example shell:curl's options correspond to the CurlOptions interface in the shell:curl client file.

import { HTTPSnippet } from 'httpsnippet';

const snippet = new HTTPSnippet({
  method: 'GET',
  url: 'http://mockbin.com/request',
});

// generate Node.js: Native output
console.log(snippet.convert('node'));

// generate Node.js: Native output, indent with tabs
console.log(
  snippet.convert('node', {
    indent: '\t',
  }),
);

isTarget

Useful for validating that a custom target is considered valid by HTTPSnippet.

const isTarget: (target: Target) => target is Target;
import { myCustomTarget } from './my-custom-target';
import { isTarget } from 'httpsnippet';

try {
  console.log(isTarget(myCustomTarget));
} catch (error) {
  console.error(error);
}

addTarget

Use addTarget to add a new custom target that you can then use in your project.

const addTarget: (target: Target) => void;
import { myCustomClient } from './my-custom-client';
import { HAR } from 'my-custom-har';
import { HTTPSnippet, addTargetClient } from 'httpsnippet';

addTargetClient(myCustomClient);

const snippet = new HTTPSnippet(HAR);
const output = snippet.convert('customTargetId');
console.log(output);

isClient

Useful for validating that a custom client is considered valid by HTTPSnippet.

const isClient: (client: Client) => client is Client;
import { myCustomClient } from './my-custom-client';
import { isClient } from 'httpsnippet';

try {
  console.log(isClient(myCustomClient));
} catch (error) {
  console.error(error);
}

addTargetClient

Use addTargetClient to add a custom client to an existing target. See addTarget for how to add a custom target.

const addTargetClient: (targetId: TargetId, client: Client) => void;
import { myCustomClient } from './my-custom-client';
import { HAR } from 'my-custom-har';
import { HTTPSnippet, addTargetClient } from 'httpsnippet';

addTargetClient('customTargetId', myCustomClient);

const snippet = new HTTPSnippet(HAR);
const output = snippet.convert('customTargetId', 'customClientId');
console.log(output);

Bugs and feature requests

Have a bug or a feature request? Please first read the issue guidelines and search for existing and closed issues. If your problem or idea is not addressed yet, please open a new issue.

Contributing

Please read through our contributing guidelines. Included are directions for opening issues, coding standards, and notes on development.

For info on creating new conversion targets, please review this guideline

Moreover, if your pull request contains TypeScript patches or features, you must include relevant unit tests.

Editor preferences are available in the editor config for easy use in common text editors. Read more and download plugins at http://editorconfig.org.

More Repositories

1

kong

🦍 The Cloud-Native API Gateway and AI Gateway.
Lua
37,159
star
2

insomnia

The open-source, cross-platform API client for GraphQL, REST, WebSockets and gRPC.
JavaScript
30,407
star
3

unirest-java

Unirest in Java: Simplified, lightweight HTTP client library.
Java
2,560
star
4

kubernetes-ingress-controller

🦍 Kong for Kubernetes: The official Ingress Controller for Kubernetes.
Go
2,127
star
5

swrv

Stale-while-revalidate data fetching for Vue
TypeScript
2,048
star
6

mockbin

Mock, Test & Track HTTP Requests and Response for Microservices
JavaScript
1,988
star
7

mashape-oauth

OAuth Modules for Node.js - Supporting RSA, HMAC, PLAINTEXT, 2,3-Legged, 1.0a, Echo, XAuth, and 2.0
JavaScript
1,781
star
8

docker-kong

🐒 Docker distribution for Kong
Shell
1,351
star
9

unirest-php

Unirest in PHP: Simplified, lightweight HTTP client library.
PHP
1,282
star
10

unirest-nodejs

Unirest in Node.js: Simplified, lightweight HTTP client library.
JavaScript
954
star
11

guardian

Remove the OAuth dance with one request.
JavaScript
640
star
12

unirest-python

Unirest in Python: Simplified, lightweight HTTP client library.
Python
432
star
13

deck

decK: Configuration management and drift detection for Kong
Go
419
star
14

apiembed

Embeddable API code snippets for your website, blog or API documentation
Pug
402
star
15

unirest-ruby

Unirest in Ruby: Simplified, lightweight HTTP client library.
Ruby
365
star
16

unirest-obj-c

Unirest in Objective-C: Simplified, lightweight HTTP client library.
Objective-C
276
star
17

kong-dist-kubernetes

Kubernetes managed Kong cluster
Shell
255
star
18

kong-plugin

Simple template to get started with custom Kong plugins
Lua
230
star
19

charts

Helm chart for Kong
Mustache
224
star
20

unirest-net

Unirest in .NET: Simplified, lightweight HTTP client library.
C#
190
star
21

lua-resty-worker-events

Cross Worker Events for Nginx in Pure Lua
Lua
186
star
22

docs.konghq.com

🦍 Source code for docs.konghq.com website.
Ruby
186
star
23

kong-oauth2-hello-world

This is a simple node.js + express.js application that shows an authorization page for the OAuth 2.0 plugin on Kong.
JavaScript
173
star
24

kong-manager

Admin GUI for Kong Gateway (Official)
TypeScript
170
star
25

lua-resty-dns-client

Lua DNS client, load balancer, and utility library
Lua
151
star
26

kong-pongo

Tooling to run plugin tests with Kong and Kong Enterprise
Lua
139
star
27

go-pdk

Kong Go Plugin Development Kit
Go
126
star
28

kong-vagrant

🐒 Vagrantfile for Kong testing and development
Shell
125
star
29

kongponents

🦍 Kong Vue Component Library
Vue
119
star
30

lua-resty-healthcheck

Healthcheck library for OpenResty to validate upstream service status
Lua
119
star
31

kong-plugin-prometheus

Prometheus plugin for Kong - this plugin has been moved into https://github.com/Kong/kong, please open issues and PRs in that repo
Lua
119
star
32

apiglossary

Open source glossary of API terms, acronyms and industry buzzwords.
95
star
33

go-plugins

A collection of Kong plugins written in Go
Go
86
star
34

go-kong

Go binding for Kong's admin API
Go
81
star
35

kong-terraform-aws

Kong Terraform Module for AWS
HCL
77
star
36

kong-build-tools

Build tools to package and release Kong
Shell
77
star
37

homebrew-kong

🐒 Homebrew tap for Kong
Ruby
69
star
38

kong-dist-cloudformation

🐒 Kong CloudFormation Stack
66
star
39

go-pluginserver

Kong Go Plugin Server
Go
66
star
40

ngx_wasm_module

Nginx + WebAssembly
C
64
star
41

kong-plugin-zipkin

A Kong plugin for propogating zipkin spans and reporting spans to a zipkin server - this plugin has been moved into https://github.com/Kong/kong, please open issues and PRs in that repo
Lua
60
star
42

kong-operator

Kong Operator for Kubernetes and OpenShift
Mustache
58
star
43

lua-multipart

Multipart Parser for Lua
Lua
55
star
44

mashape-php-library

Mashape PHP Server Library - Easily create an API in PHP. You can use it for existing services or brand new cloud components.
PHP
50
star
45

gojira

Multi-purpose tool to ease development and testing of Kong by using Docker containers
Shell
45
star
46

HARchiver

[Deprecated] Universal Lightweight Proxy for Galileo
OCaml
41
star
47

koko

koko - Control Plane for Kong Gateway [open-source]
Go
41
star
48

unirest-website

Simplified, lightweight HTTP libraries in multiple languages
HTML
39
star
49

kong-python-pdk

Write Kong plugins in Python
Python
39
star
50

go-srp

Secure Remote Password library for Go
Go
38
star
51

tcpbin

TCP Request & Response Service, written in node.js
HTML
37
star
52

kong-portal-templates

Themes, components, and utilities to help you get started with the Kong Dev Portal.
CSS
35
star
53

kong-plugin-acme

Let's Encrypt and ACMEv2 integration with Kong - this plugin has been moved into https://github.com/Kong/kong, please open issues and PRs in that repo
Lua
34
star
54

kong-mesh-dist-kubernetes

Start Kong 1.0 as a K8s sidecar
Makefile
33
star
55

kubernetes-testing-framework

Golang Integration Testing Framework For Kubernetes APIs and Controllers.
Go
32
star
56

gateway-operator

Go
32
star
57

demo-scene

🦍 a collection of demos and examples around Kong tools and technologies
JavaScript
30
star
58

docker-java8

A Dockerfile for starting a container with Java 8 installed
30
star
59

lua-kong-nginx-module

Nginx C module to allow deeper control of Nginx behaviors by Kong Lua code
Perl
30
star
60

Astronode-Broadcaster

A TCP replication server, or broadcaster, that replicates TCP commands to other TCP servers
Java
29
star
61

opentracing-lua

Opentracing Library for Lua
Lua
28
star
62

konnect-portal

Konnect OSS Dev Portal
TypeScript
28
star
63

atc-router

Expression based matching library for Kong
Rust
28
star
64

kong-js-pdk

Kong PDK for Javascript and plugin server
JavaScript
28
star
65

boss.js

Automatically load balance asyncronous jobs across multiple processes in a round-robin fashion.
JavaScript
27
star
66

kong-portal-cli

Kong Developer Portal CLI
TypeScript
25
star
67

lua-uuid

Lua library to generate UUIDs leveraging libuuid
Lua
25
star
68

insomnia-docs

This repository houses all Insomnia documentation.
JavaScript
25
star
69

lua-resty-lmdb

Safe API for manipulating LMDB databases using OpenResty/Lua.
C
24
star
70

lua-resty-aws

AWS SDK for OpenResty
Lua
22
star
71

lua-resty-timer

Extended timers for OpenResty
Perl
22
star
72

lua-resty-events

Inter process Pub/Sub pattern for Nginx worker processes
Perl
22
star
73

kong-plugin-request-transformer

Kong request transformer plugin - this plugin has been moved into https://github.com/Kong/kong, please open issues and PRs in that repo
Lua
21
star
74

lua-resty-counter

Lock-free counter for OpenResty
Perl
21
star
75

kong-plugin-session

🍪 Session plugin for Kong - this plugin has been moved into https://github.com/Kong/kong, please open issues and PRs in that repo
Lua
20
star
76

lua-pack

A library for packing and unpacking binary data.
C
20
star
77

go-apiops

Kong's Go based APIOps library
Go
18
star
78

swagger-ui-kong-theme

Plugin theme for Swagger-UI that adds snippets
JavaScript
18
star
79

api-log-format

Specification and examples of the new API logging format ALF
17
star
80

kong-plugin-serverless-functions

Kong Serverless Plugins - this plugin has been moved into https://github.com/Kong/kong, please open issues and PRs in that repo
Lua
17
star
81

apistatus

API status is a simple tool that checks if an API is online. http://apistatus.org
JavaScript
15
star
82

openresty-patches

Moved to https://github.com/Kong/kong-build-tools
Perl
14
star
83

kong-plugin-grpc-gateway

Kong Plugin to transcode REST request to gRPC - this plugin has been moved into https://github.com/Kong/kong, please open issues and PRs in that repo
Lua
14
star
84

lua-resty-consul-event

Consul Events HTTP API Wrapper
Perl
14
star
85

srp-js

Fork of node-srp modified to work in the browser
TypeScript
14
star
86

harplayer

Replay HAR logs
JavaScript
13
star
87

kong-plugin-aws-lambda

AWS Lambda plugin - this plugin has been moved into https://github.com/Kong/kong, please open issues and PRs in that repo
Lua
13
star
88

openresty-build-tools

Moved to https://github.com/Kong/kong-build-tools
Shell
13
star
89

jenkins-infrastructure

Cloudformation to create and update an ECS cluster that runs jenkins
Shell
12
star
90

kong-plugin-proxy-cache

HTTP Proxy Caching for Kong - this plugin has been moved into https://github.com/Kong/kong, please open issues and PRs in that repo
Lua
12
star
91

openapi2kong

Lib to convert OpenAPI specs into Kong specs
Lua
12
star
92

version.lua

Simple version comparison library
Lua
11
star
93

httpbin

Python
11
star
94

changelog-generator

a changelog generator focused on flexibility and ease of use
TypeScript
11
star
95

vault-kong-secrets

A Kong secrets backend for Vault
Go
11
star
96

py-postgrest

A library to work with PostgREST based APIs from Python
Python
11
star
97

priority-updater

Tool to quickly create a plugin with an updated priority
Lua
11
star
98

galileo-agent-java

Java Agent for Mashape Galileo
Java
10
star
99

kong-plugin-openwhisk

A kong plugin to invoke OpenWhisk action (serverless functions as service).
Lua
10
star
100

kong-upgrade-tests

Tests for upgrading from one Kong version to the next
Shell
10
star