Last active
May 10, 2024 08:09
-
-
Save josanua/2cea4e60734a9adf1c623547e06dbdb7 to your computer and use it in GitHub Desktop.
API Helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // ------------- general info ------------- // | |
| // HTTP | |
| https://en.wikipedia.org/wiki/HTTP | |
| // List of HTTP header fields | |
| https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields | |
| // Request methods | |
| https://en.wikipedia.org/wiki/HTTP#Request_methods | |
| // Allow methods | |
| https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 | |
| // ------------- work with clients ------------- // | |
| //--- httpie client ---// | |
| // web interface and can use in CLI is much more readable than CURL | |
| https://httpie.io/app | |
| //--- curl client ---// | |
| curl http://localhost:8888/api/tasks/123 --request POST/GET/PUT/DELETE (HTTP methods, default is GET) | |
| // or | |
| curl http://localhost:8888/api/tasks/123 -X POST/GET/PUT/DELETE | |
| // examples | |
| // GET Request: | |
| curl http://example.com | |
| curl -X POST http://example.com/resource | |
| // Set Custom Header: | |
| curl -H "Authorization: Bearer token123" http://example.com/resource | |
| // POST Request with Data: | |
| curl -X POST -d "param1=value1¶m2=value2" http://example.com/resource | |
| // POST Request with JSON Data: | |
| curl -X POST -H "Content-Type: application/json" -d '{"key1":"value1","key2":"value2"}' http://example.com/resource | |
| // Save Response to File: | |
| curl -o output.txt http://example.com | |
| // Basic Authentication: | |
| curl -u username:password http://example.com/resource | |
| // ------------- work php vanilla, php funcs ------------- // | |
| /* | |
| * work with requests | |
| */ | |
| // get request url | |
| // user superglobals | |
| $_SERVER["REQUEST_URI"]; | |
| // take /api/tasks/123 from http://localhost:8888/api/tasks/123?page=1 | |
| // use parse_url() for removing the query string | |
| $path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH); | |
| // get requests methods (GET, POST, PUT, etc.,) | |
| $_SERVER["REQUEST_METHOD"]; | |
| // Gets or sets the HTTP response status code. | |
| // return HTTP Code, http code | |
| http_response_code(404); | |
| // Send a raw HTTP header, http header, send header | |
| header(); | |
| // ------------- work cURL ------------- // | |
| /* | |
| * https://www.php.net/manual/en/ref.curl.php | |
| */ | |
| // cURL Functions | |
| curl_close() — Close a cURL session | |
| curl_copy_handle() — Copy a cURL handle along with all of its preferences | |
| curl_errno() — Return the last error number | |
| curl_error() — Return a string containing the last error for the current session | |
| curl_escape() — URL encodes the given string | |
| curl_exec() — Perform a cURL session | |
| curl_file_create() — Create a CURLFile object | |
| curl_getinfo() — Get information regarding a specific transfer | |
| curl_init() — Initialize a cURL session | |
| curl_multi_add_handle() — Add a normal cURL handle to a cURL multi handle | |
| curl_multi_close() — Close a set of cURL handles | |
| curl_multi_errno() — Return the last multi curl error number | |
| curl_multi_exec() — Run the sub-connections of the current cURL handle | |
| curl_multi_getcontent() — Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set | |
| curl_multi_info_read() — Get information about the current transfers | |
| curl_multi_init() — Returns a new cURL multi handle | |
| curl_multi_remove_handle() — Remove a multi handle from a set of cURL handles | |
| curl_multi_select() — Wait for activity on any curl_multi connection | |
| curl_multi_setopt() — Set an option for the cURL multi handle | |
| curl_multi_strerror() — Return string describing error code | |
| curl_pause() — Pause and unpause a connection | |
| curl_reset() — Reset all options of a libcurl session handle | |
| curl_setopt_array() — Set multiple options for a cURL transfer | |
| curl_setopt() — Set an option for a cURL transfer | |
| curl_share_close() — Close a cURL share handle | |
| curl_share_errno() — Return the last share curl error number | |
| curl_share_init() — Initialize a cURL share handle | |
| curl_share_setopt() — Set an option for a cURL share handle | |
| curl_share_strerror() — Return string describing the given error code | |
| curl_strerror() — Return string describing the given error code | |
| curl_unescape() — Decodes the given URL encoded string | |
| curl_version() — Gets cURL version information | |
| // cURL Work Example | |
| https://www.php.net/manual/en/curl.examples-basic.php | |
| // create curl resource, initialize a cURL session | |
| $ch = curl_init(); | |
| // set url | |
| curl_setopt($ch, CURLOPT_URL, "example.com"); | |
| //return the transfer as a string | |
| curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
| // $output contains the output string | |
| $output = curl_exec($ch); | |
| // close curl resource to free up system resources | |
| curl_close($ch); | |
| // useful functions | |
| // php.net/manual/en/function.http-build-query.php | |
| http_build_query() - Generate URL-encoded query string | |
| json_encode() - Returns the JSON representation of a value | |
| json_decode() - Decodes a JSON string | |
| https://www.php.net/manual/en/function.urlencode.php | |
| urlencode() - URL-encodes string // This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page. | |
| // example with json | |
| $query_values = json_encode($query_values); | |
| //debug($query_values); | |
| $ch = curl_init(); | |
| curl_setopt($ch, CURLOPT_POST, 1); | |
| //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query( $query_values )); | |
| curl_setopt($ch, CURLOPT_POSTFIELDS, $query_values); | |
| curl_setopt($ch, CURLOPT_URL, 'url'); | |
| curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
| curl_setopt($ch, CURLOPT_HTTPHEADER, array( | |
| "Accept: */*", | |
| "Accept-Encoding: gzip, deflate", | |
| "Cache-Control: no-cache", | |
| "Connection: keep-alive", | |
| "Content-Type: application/json", | |
| ) | |
| ); | |
| $server_output = curl_exec($ch); | |
| $response = json_decode($server_output, true); | |
| // Result Output | |
| // debug($server_output); | |
| curl_close($ch); | |
| // example from Udemy | |
| // Github Test for API testing | |
| https://docs.github.com/en/rest/activity/events?apiVersion=2022-11-28#list-public-events-for-a-user | |
| // const API_ADDR = 'https://randomuser.me/api'; | |
| //const API_ADDR = 'https://api.unsplash.com/photos/random'; | |
| //const API_ADDR = 'https://api.github.com/user/starred/httpie/httpie'; | |
| //const API_ADDR = 'https://api.github.com/user/josanua/wpforpro_underscore'; | |
| //const API_ADDR = 'https://api.github.com/repos/josanua/php-photogallery-oop/branches'; | |
| const API_ADDR = 'https://api.github.com/gists'; | |
| $curlSession = curl_init(); | |
| $headers = [ | |
| // "Authorization: Client-ID 7r06Y5mNPA32P0p-jvRIXr7dKhs3U" | |
| // for Github authorization procedure | |
| "Authorization: Client-ID ", | |
| "Accept: application/vnd.github+json", | |
| // "User-Agent: josanua" | |
| ]; | |
| // single steps methods | |
| // curl_setopt($curlSession, CURLOPT_URL, API_ADDR); | |
| // curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true); | |
| // array method | |
| curl_setopt_array($curlSession, [ | |
| CURLOPT_URL => API_ADDR, | |
| CURLOPT_RETURNTRANSFER => true, | |
| CURLOPT_HTTPHEADER => $headers, | |
| // CURLOPT_HEADER => true, | |
| CURLOPT_USERAGENT => "josanua", | |
| // CURLOPT_CUSTOMREQUEST => "GET" // HTTP verbs | |
| ]); | |
| $response = curl_exec($curlSession); | |
| // get status code | |
| $statusCode = curl_getinfo($curlSession, CURLINFO_HTTP_CODE); | |
| //$contentType = curl_getinfo($curlSession, CURLINFO_CONTENT_TYPE); | |
| //$contentLength = curl_getinfo($curlSession, CURLINFO_CONTENT_LENGTH_DOWNLOAD); | |
| curl_close($curlSession); | |
| var_dump($statusCode); | |
| var_dump($response); | |
| // work with query | |
| // clean address from url params | |
| // url 'api/tasks?page=1' will be '/api/tasks' | |
| echo parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH); | |
| // create an array with path parts | |
| $path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH); | |
| $parts = explode("/", $path); | |
| // examples with response code | |
| $path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH); | |
| $parts = explode("/", $path); | |
| $resource = $parts[2]; | |
| $id = $parts[3] ?? null; | |
| echo $resource. ", "; | |
| echo $_SERVER["REQUEST_METHOD"]; | |
| // create response codes | |
| if($resource != 'tasks') { | |
| // header("HTTP/1.1 404 Not Found"); | |
| http_response_code(404); // recommended way to use response codes | |
| exit; | |
| } | |
| //--- my old API work ---// | |
| // $merchantHandler = 'https://ecomm.maib.md:4455/ecomm2/MerchantHandler'; | |
| // cURL Connection | |
| function curlConnection($merchantHandler){ | |
| // For log POST Header | |
| ob_start(); | |
| $out = fopen('/public_html/curl-merchant.log', 'w'); | |
| //settings | |
| $addr = curl_init($merchantHandler); | |
| curl_setopt($addr, CURLOPT_VERBOSE, 1); | |
| curl_setopt($addr, CURLOPT_CERTINFO, true); | |
| curl_setopt($addr, CURLOPT_RETURNTRANSFER, true); | |
| curl_setopt($addr, CURLOPT_SSL_VERIFYPEER, false); | |
| curl_setopt($addr, CURLOPT_SSL_VERIFYHOST, false); | |
| curl_setopt($addr, CURLOPT_CAINFO, 'absoluth/path/cacert.pem'); | |
| curl_setopt($addr, CURLOPT_SSLCERT,'absoluth/path/pcert.pem'); | |
| curl_setopt($addr, CURLOPT_SSLKEY, 'absoluth/path/key.pem'); | |
| curl_setopt($addr, CURLOPT_SSLCERTPASSWD, ''); | |
| curl_setopt($addr, CURLOPT_HEADER, 0); | |
| curl_setopt($addr, CURLOPT_POST, TRUE); | |
| curl_setopt($addr, CURLOPT_STDERR, $out); | |
| // curl_setopt($addr, CURLOPT_POSTFIELDS, $postdata); | |
| $response = curl_exec($addr); | |
| // return $response; | |
| // For log POST Header | |
| fclose($out); | |
| $debug = ob_get_clean() . $response; | |
| if( $response === false) | |
| { | |
| echo 'Curl error: ' . curl_error($addr); | |
| } | |
| else | |
| { | |
| echo 'Operation completed without any errors'; | |
| curl_close($addr); | |
| } | |
| } | |
| function testTLS(){ | |
| $ch = curl_init(); | |
| curl_setopt($ch, CURLOPT_URL, "https://www.howsmyssl.com/a/check"); | |
| curl_setopt($ch, CURLOPT_SSLVERSION, 6); | |
| curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
| $response = curl_exec($ch); | |
| curl_close($ch); | |
| $tlsVer = json_decode($response, true); | |
| echo "<h1>Your TSL version is: <u>" . ( $tlsVer['tls_version'] ? $tlsVer['tls_version'] : 'no TLS support' ) . "</u></h1>"; | |
| } | |
| // curlConnection($merchantHandler); | |
| testTLS(); | |
| //--- helpers, my code, my helpers code, utils, ---// | |
| // Error handler which return JSON responses | |
| class ErrorHandler | |
| { | |
| public static function handleException(Throwable $exception): void | |
| { | |
| http_response_code(500); | |
| echo json_encode([ | |
| "code" => $exception->getCode(), | |
| "message" => $exception->getMessage(), | |
| "file" => $exception->getFile(), | |
| "line" => $exception->getLine() | |
| ]); | |
| } | |
| } | |
| // Process requests | |
| class TaskController | |
| { | |
| public function processRequest(string $method, ?string $id): void | |
| { | |
| if ($id === null) { | |
| if ($method == "GET") { | |
| echo "index"; | |
| } elseif ($method == "POST") { | |
| echo "create"; | |
| } else { | |
| $this->respondMethodNotAllowed("GET, POST"); | |
| } | |
| } else { | |
| switch ($method) { | |
| case "GET": | |
| echo "show $id"; | |
| break; | |
| case "PATCH": | |
| echo "update $id"; | |
| break; | |
| case "DELETE": | |
| echo "delete $id"; | |
| break; | |
| default: | |
| $this->respondMethodNotAllowed("GET, PATCH, DELETE"); | |
| } | |
| } | |
| } | |
| private function respondMethodNotAllowed(string $allowed_methods): void | |
| { | |
| http_response_code(405); | |
| header("Allow: $allowed_methods"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment