PHP Classes

PHP HTTP Code Sample Snippet Generator in Multiple Languages: Generate code snippets to make HTTP requests

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
Not enough user ratingsTotal: 49 All time: 10,738 This week: 52Up
Version License PHP version Categories
httpsnippet 1.0.0MIT/X Consortium ...7HTTP, Code Generation, PHP 7
Description 

Author

This package can generate code snippets to make HTTP requests.

It can compose an HTTP request from parameters to send that request, for instance, the request URL, HTTP method, request headers, parameters in the request body, HTTP version, cookie values, etc...

The package can generate code in different languages using different libraries to send the configured HTTP request.

Currently, the package can generate code to send the request using:

- PHP code with the Curl extension

- C code using the libcurl library

- C# code using the HTTP Client class

- C# using RestSharp HTTP client library

- PHP using the Guzzle package

- Shell script using the curl command

- Shell script using the wget command

Innovation Award
PHP Programming Innovation award nominee
September 2023
Number 6
Many sites and applications now provide APIs. Developers that want to use those APIs must write code to send HTTP requests to those APIs to certain URLs using specific parameters.

The actual code that they need to write depends on the programming language and libraries that they can use with that language to send HTTP requests to the APIs they want to call.

This package provides a general solution to generate code to call certain APIs in several languages using different libraries.

Manuel Lemos
Picture of Isa Eken
  Performance   Level  
Innovation award
Innovation award
Nominee: 14x

 

Example

#!/usr/bin/php
<?php

require_once __DIR__ . '/../vendor/autoload.php';

use
GuzzleHttp\Psr7\Request;
use
IsaEken\HttpSnippet\HttpSnippet;

$method = 'GET';
$url = null;
$headers = [];
$body = null;
$language = null;
$output = null;

function
help(): never
{
    echo
'Usage: httpsnippet --url= --language= [options]' . PHP_EOL;

    echo
PHP_EOL;
    echo
'Options:' . PHP_EOL;
    echo
' --help : Displays this screen' . PHP_EOL;
    echo
' --method=GET : Set the request method' . PHP_EOL;
    echo
' --url=http://example.com : Set the url' . PHP_EOL;
    echo
' --header="Content-Type: application/json" : Add a header' . PHP_EOL;
    echo
' --body="{}" : Set the body' . PHP_EOL;
    echo
' --language=php.curl : Set the language' . PHP_EOL;
    echo
' --output= : Set the output' . PHP_EOL;
    echo
PHP_EOL;
    echo
'Examples:' . PHP_EOL;
    echo
' httpsnippet --url=http://example.com --language=php.curl' . PHP_EOL;
    echo
' httpsnippet --url=http://example.com --language=php.curl --output=snippet.php' . PHP_EOL;
    echo
' httpsnippet --url=http://example.com --language=shell.curl --output=php://stdout' . PHP_EOL;
    echo
PHP_EOL;
    echo
'Languages:' . PHP_EOL;

    foreach (
HttpSnippet::getTargets() as $target) {
        echo
' ' . $target['title'] . ' : ' . $target['name'] . PHP_EOL;
        echo
' ' . $target['link'] . PHP_EOL;
        echo
' ' . $target['description'] . PHP_EOL;
        echo
PHP_EOL;
    }

    exit(
0);
}

foreach (
$argv as $item) {
    if (
str_starts_with($item, '--help')) {
       
help();
    }

    if (
str_starts_with($item, '--method=')) {
       
$method = substr($item, 9);
    }

    if (
str_starts_with($item, '--url=')) {
       
$url = substr($item, 6);
    }

    if (
str_starts_with($item, '--header=')) {
       
$headers[] = substr($item, 9);
    }

    if (
str_starts_with($item, '--body=')) {
       
$body = substr($item, 7);
    }

    if (
str_starts_with($item, '--language=')) {
       
$language = substr($item, 11);
    }

    if (
str_starts_with($item, '--output=')) {
       
$output = substr($item, 9);
    }
}

if (
$url === null) {
    echo
'Error: --url is required.' . PHP_EOL;
    exit(
1);
}

if (
$language === null) {
    echo
'Error: --language is required.' . PHP_EOL;
    exit(
1);
}

$output = $output ?? 'php://stdout';
$output = fopen($output, 'w');
$headers = array_map(fn($item) => explode(':', $item, 2), $headers);

$request = new Request(
   
$method,
   
$url,
   
$headers,
   
$body,
);

$httpSnippet = HttpSnippet::make($request, $language);

echo
$httpSnippet->generate(true);


Details

httpsnippet

Latest Version on Packagist GitHub Tests Action Status Total Downloads

httpsnippet is a PHP package that enables you to make HTTP request codes for any language. This can be particularly useful for developers who are looking to perform HTTP requests using various programming languages.

Example

Here?s how you can create a GET request code in PHP:

$request = new \IsaEken\HttpSnippet\Request(
    method: 'GET',
    uri: 'https://example.com'
);

echo \IsaEken\HttpSnippet\HttpSnippet::make($request, 'php.curl')->toString();

Installation

You can install this package via composer:

composer require isaeken/httpsnippet

Usage

The httpsnippet package allows you to create HTTP request codes in various programming languages. Below are the steps to use this package:

1. Import the Package

Before you start, make sure that you have installed the package via composer. If not, you can install it by running:

composer require isaeken/httpsnippet

Now, import the httpsnippet package in your PHP script:

use IsaEken\HttpSnippet\HttpSnippet;
use IsaEken\HttpSnippet\Request;

require_once __DIR__ . '/vendor/autoload.php';

2. Create a Request

Next, create a request object. You can do this by passing the request method, URI, headers, and body to the Request class:

$request = new Request(
    method: 'GET',
    uri: 'https://example.com',
    headers: [
        'Accept' => 'application/json',
    ],
    body: [
        'foo' => 'bar',
    ],
    version: '1.1',
    cookies: [
        'foo' => 'bar',
    ],
);

3. Generate the Request Code

Now, use the make method of the HttpSnippet class to generate the request code for the desired programming language. Pass in the request object and the target programming language as parameters.

$code = HttpSnippet::make($request, 'language.identifier');

For instance, to generate the code in PHP using cURL, you would do:

$code = HttpSnippet::make($request, 'php.guzzle');

4. Output or Use the Code

You can now output or use the generated code as needed. For example, to print the code:

echo $code->toString();

// output:
// <?php
//
// $client = new \GuzzleHttp\Client();
//
// $response = $client->request(
//     'GET',
//     'https://example.com',
//     [
//         'body' => '{"foo":"bar"}',
//         'headers' => [
//             "Accept" => "application/json",
//             "Cookie" => "foo=bar",
//         ],
//     ],
// );
// 
// echo $response->getBody();

Or, to save the code to a file:

file_put_contents('code.txt', $code->toString());

Supported Languages and Identifiers

The following languages and identifiers are supported:

| Language | Identifier | Ready for use? | | --- |----------------------------|----------------| | C | libcurl | ? | | C# | csharp.httpclient | ? | | C# | csharp.restsharp | ? | | PHP | php.curl | ? | | PHP | php.guzzle | ? | | Shell | shell.curl | ? | | Shell | shell.wget | ? |

Testing

Run the tests with:

composer test

Changelog

All notable changes to httpsnippet will be documented in this file

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security-related issues, please email hello@isaeken.com.tr instead of using the issue tracker.

License

The MIT License (MIT). Please see License File for more information.


  Files folder image Files (62)  
File Role Description
Files folder image.github (1 directory)
Files folder imagebin (1 file)
Files folder imageconfig (1 file)
Files folder imagesrc (4 files, 6 directories)
Files folder imagetests (3 files, 1 directory)
Plain text file .editorconfig Data Auxiliary data
Plain text file .php_cs.dist.php Example Example script
Plain text file CHANGELOG.md Data Auxiliary data
Plain text file composer.json Data Auxiliary data
Plain text file LICENSE.md Lic. License text
Plain text file phpunit.xml Data Auxiliary data
Plain text file README.md Doc. Read me

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads Download Rankings  
 100%
Total:49
This week:0
All time:10,738
This week:52Up