PHP code example of karewan / knhttp

1. Go to this page and download the library: Download karewan/knhttp library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

karewan / knhttp example snippets


/** @var KnResponse */
$res = (new KnRequest())
	->get("https://jsonplaceholder.typicode.com/todos/1")
	->execForJson();

/** @var KnResponse */
$res = (new KnRequest())
	->post("https://jsonplaceholder.typicode.com/posts")
	->setJsonBody([
		'title' => 'foo',
		'body' => 'bar',
		'userId' => 1
	])
	->execForJson();

/** @var KnResponse */
$res = (new KnRequest())
	->put("https://jsonplaceholder.typicode.com/posts/1")
	->setJsonBody([
		'title' => 'foo',
		'body' => 'bar',
		'userId' => 1
	])
	->execForJson();

/** @var KnResponse */
$res = (new KnRequest())
	->delete("https://jsonplaceholder.typicode.com/todos/1")
	->execForJson();

/** @var KnResponse */
$res = (new KnRequest())
	->patch("https://jsonplaceholder.typicode.com/todos/1")
	->execForJson();

/** @var KnResponse */
$res = (new KnRequest())
	->patch("https://fakerestapi.azurewebsites.net/api/v1/activities")
	->execForHeaders();

/** @var KnResponse */
$res = (new KnRequest())
	->option("https://fakerestapi.azurewebsites.net/api/v1/activities")
	->execForHeaders();

/** @var KnResponse */
$res = (new KnRequest())
	->request("DELETE", "https://jsonplaceholder.typicode.com/todos/1")
	->execForJson();

$req1 = (new KnRequest())
	->get("https://jsonplaceholder.typicode.com/todos/1")
	->setForJson();

$req2 = (new KnRequest())
	->get("https://jsonplaceholder.typicode.com/todos/2")
	->setForJson();

/** @var KnResponse[] */
$results = KnRequest::execMulti([$req1, $req2]);

// Enable verify SSL
$req->setVerifySsl(true);

//  Check if SSL is verified
$isVerifySsl = $req->isVerifySsl();

// Request timeout in seconds
$req->setConnectTimeout(10);

// Request connect timeout
$connectTimeout = $req->getConnectTimeout();

// Set request timeout in seconds
$req->setTimeout(300);

// Get request timeout
$timeout = $req->getTimeout();

// Set user agent
$req->setUserAgent("MyApp/1.0.0");

// Get the user agent
$userAgent = $req->getUserAgent();

// Set one header to the request
$req->setHeader("Api-Key", "xxx");

// Remove one header to the request
$req->setHeader("Api-Key", null);

// Set multiple headers to the request
$req->setHeaders([
	"Api-Key" => "xxx",
	"X-Proto" => "CustomProto"
]);

// Get request headers
$headers = $req->getHeaders();

// Remove all added headers from the request
$req->clearHeaders();

// Set a path param (https://jsonplaceholder.typicode.com/todos/{id})
$req->setPathParam("id", "1");

// Remove a path param
$req->setPathParam("id", null);

// Set multiple path param (https://jsonplaceholder.typicode.com/{type}/{id})
$req->setPathParams([
	"type" => "todos",
	"id" => "1"
]);

// Get the req path params
$pathParams = $req->getPathParams();

// Remove all added path params from the request
$req->clearPathParams();

// Set basic auth
$req->setBasicAuth("username", "password");

// Get the req basic auth
$basicAuth = $req->getBasicAuth();

// Remove basic auth
$req->clearBasicAuth();

// Set a query param to be added to the URL
$req->setQueryParam("limit", "10");

// Remove a query param
$req->setQueryParam("limit", null);

// Set multiple query param to be added to the URL
$req->setQueryParams([
	"offset" => "10",
	"limit" => "10"
]);

// Get the req query params
$queryParams = $req->getQueryParams();

// Remove all added query params from the request
$req->clearQueryParams();

// Set a CURL option
$req->setCurlOption(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

// Set multiple CURL option
$req->setCurlOptions([
	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
	CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2
]);

// Get the req CURL options
$curlOptions = $req->getCurlOptions();

// Remove all added curl options from the request
$req->clearCurlOptions();

// Set an URL encoded form body for POST and PUT
$req->setFormBody([
	"data1" => "xxx",
	"field3" => "xxx"
]);

// Get the req form body
$formBody = $req->getFormBody();

// Set an formData body for POST and PUT
$req->setFormDataBody([
	"data1" => "xxx",
	"field3" => "xxx"
]);

// Get the req formData body
$formDataBody = $req->getFormDataBody();

// Set an string body for POST and PUT
$req->setStringBody("mybody");

// Get the req string body
$stringBody = $req->getStringBody();

// Set an JSON body for POST and PUT
$req->setJsonBody([
	"jsonField1" => "xxx",
	"keyboard" => [
		"azerty" => "bad for english",
		"qwerty" => "bad for french"
	]
]);

// Get the req JSON body
$jsonBody = $req->getJsonBody();

// Set an file body for POST and PUT
$req->setFileBody("myfile.txt");

// Get file body path
$fileBodyPath = $req->getFileBody();

// Set an stream body for POST and PUT
$req->setStreamBody($mystream);

// Remove all added bodies from the request
$req->clearBodies();

/** @var KnResponse */
$req->execForString();

// Set request to a string response (for execMulti)
$req->setForString();

/** @var KnResponse */
$req->execForJson();

// Set request to a JSON response (for execMulti)
$req->setForJson();

/** @var KnResponse */
$req->execForFile();

// Set request to a file response (for execMulti)
$req->setForFile();

/** @var KnResponse */
$req->execForStream();

// Set request to a stream response (for execMulti)
$req->setForStream();

// Get the raw req Url
$url = $req->getUrl();

// Get the prepared URL (including query and path params)
$preparedUrl = $req->getPreparedUrl();

// Get the req method
$method = $req->getMethod();

/**
 * Returns `true` if there are no errors
 * @return bool
 */
$success = $res->isSuccessful();

/**
 * Returns the HTTP code (0 == error)
 * @return int
 */
$httpCode = $res->getHttpCode();

/**
 * Returns the response headers
 * @return array<string,string>
 */
$headers = $res->getHeaders();

/**
 * Returns the response data
 * @return mixed
 */
$data = $res->getData();

/**
 * Returns the last error code (0 == no error)
 * See constants KnResponse::ERROR_
 * @return int
 */
$error = $res->getError();

/**
 * Returns the error label (constant name of the error)
 * TODO: to be replaced with an enum in a new version with breaking changes
 * @return string
 */
$errorLabel = $res->getErrorLabel();

/**
 * Returns the CURL error (null == no error)
 * @return null|string
 */
$curlError = $res->getCurlError();

/**
 * Returns the exception full stack trace (null == no exception)
 * @return null|string
 */
$exception = $res->getException();

/**
 * Returns the full error trace (for example => logging purposes)
 * @param bool $withHeaders