Skip to content

Instantly share code, notes, and snippets.

@Scemist
Last active August 7, 2022 12:37
Show Gist options
  • Save Scemist/08141ff20f4f980fac8b1276576ed711 to your computer and use it in GitHub Desktop.
Save Scemist/08141ff20f4f980fac8b1276576ed711 to your computer and use it in GitHub Desktop.
Modern Essential PHP Rest Api Concept
<?php
function getSimpleData()
{
$url = 'https://reqres.in/api/users?page=2';
// stream_context_set_default([
// 'http' => [
// 'proxy' => '0.0.0.0:80'
// ]
//]);
$response = file_get_contents($url);
$response = json_encode(json_decode($response), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
echo "<pre>{$response}</pre>";
}
// getSimpleData();
<?php
function postSendingData()
{
$url = 'https://reqres.in/api/users';
$request_content = <<<JSON
{
"name": "Scemist",
"job": "Developer"
}
JSON;
$context = stream_context_create([
'http' => [
'method' => 'POST',
'content' => $request_content,
'header' => 'Content-type: application/json',
// 'proxy' => '0.0.0.0:80'
]
]);
$response = file_get_contents($url, false, $context);
$response = json_encode(json_decode($response), JSON_PRETTY_PRINT);
echo "<pre>{$response}</pre>";
}
// postSendingData();
<?php
function postSendingToken()
{
$url = 'https://gorest.co.in/public/v2/users'; .
$token = 'fh2498hf284hf23uhds2938d3jhsiu3hd9238d2ijwsi2uwhds9238dh23uih398'; // Aleatory string representing GoRest token
$request_content = <<<JSON
{
"name": "Johnny B Good",
"gender": "male",
"email": "nothings@all.com",
"status": "active"
}
JSON;
$context = stream_context_create([
'http' => [
'method' => 'POST',
'content' => $request_content,
'header' => [
'Content-type: application/json',
"Authorization: Bearer {$token}"
],
// 'proxy' => '0.0.0.0:80',
'ignore_errors' => true,
]
]);
$response = file_get_contents($url, false, $context);
$response = json_encode(json_decode($response), JSON_PRETTY_PRINT);
echo "<pre>{$response}</pre>";
}
// postSendingToken();
<?php
function postUpdateWithToken($user_id = 4609)
{
$url = "https://gorest.co.in/public/v2/users/{$user_id}";
$token = 'fh2498hf284hf23uhds2938d3jhsiu3hd9238d2ijwsi2uwhds9238dh23uih398'; // Aleatory string representing GoRest token
$request_content = <<<JSON
{
"name": "Lucas Scemist",
"email": "nothing@all.com",
"status": "inactive"
}
JSON;
$context = stream_context_create([
'http' => [
'method' => 'PATCH',
'content' => $request_content,
'header' => [
'Content-type: application/json',
"Authorization: Bearer {$token}"
],
// 'proxy' => '0.0.0.0:80',
'ignore_errors' => true,
]
]);
// $stream = fopen($url, 'r', false, $context);
// $response = stream_get_contents($stream);
// fclose($stream);
$response = file_get_contents($url, false, $context);
$response = json_encode(json_decode($response), JSON_PRETTY_PRINT);
echo "<pre>{$response}</pre>";
}
// postUpdateWithToken();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment