← Back to PHP Course | Chapter 15: Web Development | Lesson 5 of 12

PHP API Development

एक API बनाना दूसरे programs के लिए एक menu design करने जैसा है, decide करना कि कौन से addresses और requests allowed हैं। यह apps और websites को आपके साथ data swap करने देता है एक orderly तरीके से।
Syntax
php
switch ($_SERVER["REQUEST_METHOD"]) {
    case "GET":    // read
        break;
    case "POST":   // create
        break;
    case "PUT":    // update
        break;
    case "DELETE": // remove
        break;
}

REST APIs Design करना

एक API बनाने का मतलब है यह design करना कि कौन से URLs कौन से resources represent करते हैं और हर एक पर कौन से HTTP methods valid हैं -- पढ़ने के लिए GET, बनाने के लिए POST, update करने के लिए PUT/PATCH, हटाने के लिए DELETE।

उदाहरण: Designing REST APIs

php
<?php
// Set `$_SERVER['REQUEST_METHOD']` to 'GET'
$_SERVER['REQUEST_METHOD'] = 'GET';
// Print "GET /users -- read\n" to the output
echo "GET /users -- read\n";
// Print "POST /users -- create\n" to the output
echo "POST /users -- create\n";
// Print "PUT /users/1 -- update\n" to the output
echo "PUT /users/1 -- update\n";
// Print "DELETE /users/1 -- remove" to the output
echo "DELETE /users/1 -- remove";
?>

JSON Output Formatting

Well-formed responses सिर्फ data return करने से आगे जाते हैं: consistent status codes, एक predictable JSON shape, और clear error messages सब मिलकर एक API को दूसरे developers के लिए integrate करना आसान बनाते हैं।

उदाहरण: JSON Output Formatting

php
<?php
// Call `header("Content-Type: application/json")`
header("Content-Type: application/json");
// Call `http_response_code(200)`
http_response_code(200);
// Print `json_encode(["status" => "ok", "data" => ["id" => 1]])` to the output
echo json_encode(["status" => "ok", "data" => ["id" => 1]]);
?>

Request Methods पढ़ना

एक single endpoint script के अंदर $_SERVER[REQUEST_METHOD] पर branch करना एक route को GET, POST, PUT, और DELETE अलग-अलग handle करने देता है, यह matching करते हुए कि REST कैसे उम्मीद करता है कि एक resource URL कई operations support करे।

उदाहरण: Reading Request Methods

php
<?php
// Set `$_SERVER['REQUEST_METHOD']` to 'PUT'
$_SERVER['REQUEST_METHOD'] = 'PUT';
// Switch on `$_SERVER['REQUEST_METHOD']` and branch by matching case
switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET': echo "Reading"; break;
    case 'PUT': echo "Updating"; break;
    case 'DELETE': echo "Deleting"; break;
}
?>

API Errors Handle करना

सही HTTP status code return करना -- malformed request के लिए 400, missing या invalid token के लिए 401, न मौजूद resource के लिए 404 -- API clients को error text parse करने के बजाय programmatically react करने देता है।

उदाहरण: Handling API Errors

php
<?php
// Call `http_response_code(404)`
http_response_code(404);
// Print `json_encode(["error" => "Resource not found"])` to the output
echo json_encode(["error" => "Resource not found"]);
?>

Simple Token Authentication

एक simple token-authentication scheme हर request पर Authorization header में एक secret value check करता है, कोई protected logic चलने से पहले वे calls reject करते हुए जिनमें एक valid token न हो।

उदाहरण: Simple Token Authentication

php
<?php
// Declare `$validToken`, set to "secret-token"
$validToken = "secret-token";
// Declare `$authHeader`, set to "Bearer wrong-token"
$authHeader = "Bearer wrong-token";
// Check whether `$authHeader !== "Bearer $validToken"`
if ($authHeader !== "Bearer $validToken") {
    // Call `http_response_code(401)`
    http_response_code(401);
    // Print `json_encode(["error" => "Unauthorized"])` to the output
    echo json_encode(["error" => "Unauthorized"]);
}
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी API से JSON error responses के बजाय HTML errors return करना।
  2. request method को ignore करना, ताकि एक GET और एक POST same treat हों।
  3. request fail होने पर भी हमेशा status 200 return करना।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.