Skip to content
Qyubie Learn
Web Development courseLesson 10 of 20 · tap to see all lessons

Web Development · Beginner

API Fundamentals: HTTP Methods, Status Codes, JSON, fetch, PHP JSON Endpoints, and Git Branches

Learn how apps talk through APIs: HTTP methods and status codes, JSON, calling a public API with fetch, building a PHP JSON endpoint, and Git branches and merges.

  • Qyubie Learn Editorial Team
  • Published
  • 15 min read

Includes 1 exercise and 2 quick checks you can do right here.

So far, servers have answered with whole HTML pages. Modern apps work differently: the page loads once, then JavaScript asks the server for just the data it needs, and updates the page itself. A weather widget, a "load more" button, a live search box, and a mobile app all work this way, through APIs. This lesson explains how APIs communicate, then you'll call one and build one. It ends with Git branches, the way teams work on features side by side.

By the end of this lesson you will be able to:

  • explain what an API is and how client and server communicate through one,
  • use HTTP methods and status codes the way REST APIs do,
  • read and write JSON,
  • call a public API from JavaScript with fetch, and handle errors,
  • create a basic JSON endpoint in PHP, and
  • create, merge, and resolve conflicts between Git branches.

What an API is

An API (Application Programming Interface) is a set of rules one program uses to ask another for data or actions. On the Web, an API is usually a set of URLs, called endpoints, that return data instead of web pages:

RequestA web page returnsAn API returns
GET /students/7HTML for a person to read{"id": 7, "name": "Ana Reyes"} for a program to use

The same client-server cycle from lesson 1 applies; only the content changes. Because the answer is plain data, any client can use it: your website's JavaScript, a mobile app, another server, or a Python script. That's why one backend can serve a website and a mobile app at the same time.

HTTP requests, responses, and status codes

An API request is an ordinary HTTP request, and the status code of the response matters even more than on web pages, because programs decide what to do based on it:

CodeNameMeaning in an API
200OKsuccess; here's the data
201Createda new item was created (after POST)
204No Contentsuccess, nothing to send back (often after DELETE)
400Bad Requestthe request was malformed or the data invalid
401Unauthorizedyou need to sign in (no valid login)
403Forbiddenyou're signed in but not allowed to do this
404Not Foundno such item or endpoint
422Unprocessable Contentthe data failed validation (some APIs use 400)
500Internal Server Errorthe server's code failed

Remember the groups: 2xx worked, 4xx the client must fix something, 5xx the server must fix something.

GET, POST, PUT/PATCH, and DELETE

A REST API uses URLs for things (nouns) and HTTP methods for actions (verbs). Here's a typical design for students:

Method + endpointActionCRUDSuccess code
GET /api/studentslist studentsRead200
GET /api/students/7get student 7Read200 (404 if missing)
POST /api/studentscreate a student from the request bodyCreate201
PUT /api/students/7replace student 7 entirelyUpdate200
PATCH /api/students/7change some fields of student 7Update200
DELETE /api/students/7delete student 7Delete204
  • GET only reads. It must never change data, because browsers, caches, and search engines repeat GET requests freely.
  • POST creates. Sending it twice usually creates two items.
  • PUT sends the whole item; PATCH sends only the fields that change: {"course": "BSIT"}.
  • DELETE removes.

Quick check

A mobile app lets a user change only their profile photo. Which request fits a REST API best?

JSON

APIs almost always send data as JSON (JavaScript Object Notation): text that looks like JavaScript objects and arrays.

{
  "id": 7,
  "name": "Ana Reyes",
  "course": "BSCS",
  "enrolled": true,
  "gwa": 1.75,
  "adviser": null,
  "subjects": ["CS 324", "CS 325"]
}

JSON's rules are stricter than JavaScript's: keys and strings use double quotes, there are no trailing commas, and no comments. The value types are string, number, boolean, null, array, and object.

Converting between JSON text and JavaScript values:

Try it · JavaScript

Output:

Ana Reyes
2
{"name":"Ana Reyes","subjects":["CS 324","CS 325"],"gwa":1.5}
{
  "ok": true,
  "items": [
    1,
    2
  ]
}

Consuming a public API with fetch

fetch(url) sends an HTTP request from JavaScript. It's asynchronous: the request takes time, so fetch returns a Promise, a value that will be ready later. await pauses until it is.

This example calls JSONPlaceholder, a free practice API with fake data. Press Run; it makes a real request:

Try it · JavaScript

Output:

Status: 200 true
Leanne Graham
Sincere@april.biz
Gwenborough

Two awaits are needed: the first waits for the response to start arriving (its status and headers), and the second, response.json(), waits for the whole body and parses it.

Handling errors

Two different things can go wrong, and they look different:

Try it · JavaScript

Output:

Ervin Howell
Could not load user: Server answered 404
none
  • fetch only rejects (jumps to catch) on network failures: no internet, a blocked request, a wrong domain.
  • A 404 or 500 is not an exception: fetch succeeds and you must check response.ok (true for 2xx) yourself. Forgetting this is the most common fetch bug.

Sending data with POST

Try it · JavaScript

Output:

201
101 Hackathon

The Content-Type: application/json header tells the server the body is JSON. (JSONPlaceholder only pretends to save the post; it always answers with id 101.)

Showing API data on a page

On a real page, you'd put the results into the DOM (lesson 7) and handle three situations: loading, error, and empty. Lesson 15 does this in React.

Try it · HTML & CSS

Preview (index.html, updates as you type)

Exercise · JavaScript

Fetch a post

Fetch https://jsonplaceholder.typicode.com/posts/3, check response.ok, and print the post's id and userId on one line like Post 3 by user 1.

Expected output
Post 3 by user 1
Hint

const res = await fetch(url); if (!res.ok) throw new Error(res.status); const post = await res.json(); console.log(Post ${post.id} by user ${post.userId});

Show a solution

Try it yourself first — you learn more from a wrong attempt than from reading an answer.

const res = await fetch("https://jsonplaceholder.typicode.com/posts/3");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const post = await res.json();
console.log(`Post ${post.id} by user ${post.userId}`);

Creating a basic PHP JSON endpoint

Your own server can be an API too. A JSON endpoint in PHP does three things differently from a page: it sends a Content-Type: application/json header, prints json_encode(...) instead of HTML, and sets a meaningful status code.

A students.php endpoint that lists students, or returns one by ?id=:

<?php
header("Content-Type: application/json");

// In a real endpoint these rows come from the database (lesson 8).
$students = [
    ["id" => 1, "name" => "Ana Reyes", "course" => "BSCS"],
    ["id" => 2, "name" => "Ben Cruz", "course" => "BSIT"],
];

if (isset($_GET["id"])) {
    $id = filter_var($_GET["id"], FILTER_VALIDATE_INT);
    $match = array_values(array_filter($students, fn($s) => $s["id"] === $id));
    if (!$match) {
        http_response_code(404);
        echo json_encode(["error" => "Student not found"]);
        exit;
    }
    echo json_encode($match[0]);
    exit;
}

echo json_encode($students);

Output for GET students.php?id=2:

{"id":2,"name":"Ben Cruz","course":"BSIT"}

Requesting students.php?id=9 returns status 404 with {"error":"Student not found"}, and students.php alone returns the whole list. Open them in your browser, or call them with fetch from a page.

Receiving JSON. When a client POSTs JSON (as in the fetch example above), PHP's $_POST stays empty: $_POST only reads form-encoded data. Read the raw body and decode it instead:

<?php
header("Content-Type: application/json");

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    http_response_code(405);                  // Method Not Allowed
    echo json_encode(["error" => "Use POST"]);
    exit;
}

$input = json_decode(file_get_contents("php://input"), true);   // true: as an array
$name = trim($input["name"] ?? "");
$course = $input["course"] ?? "";

$errors = [];
if ($name === "") $errors["name"] = "Name is required.";
if (!in_array($course, ["BSCS", "BSIT"], true)) $errors["course"] = "Choose BSCS or BSIT.";

if ($errors) {
    http_response_code(422);
    echo json_encode(["errors" => $errors]);
    exit;
}

// ... INSERT with a prepared statement (lesson 8) ...
http_response_code(201);
echo json_encode(["id" => 3, "name" => $name, "course" => $course]);

Output for a POST with {"name":"Cara Lim","course":"BSCS"}:

{"id":3,"name":"Cara Lim","course":"BSCS"}

Everything from lessons 5 and 8 still applies to an API: validate every field, use prepared statements, and never trust the client. The difference is that errors come back as JSON with a 4xx status, for the client's code to show to the user.

Git branches, merging, and conflicts

So far you've committed straight to main. On a team, or even alone, it's safer to build each feature on a branch: a separate line of commits. main stays working while the feature is unfinished, and the branch is merged in when it's ready.

main:     A───B───────────E  (merge)
               \         /
feature:        C───D───┘
git switch -c feature/student-api    # create a branch and move to it
# ... edit, then commit as usual ...
git add .
git commit -m "Add students JSON endpoint"
git push -u origin feature/student-api   # share the branch on GitHub

git switch main                      # back to main
git pull                             # get the latest main
git merge feature/student-api        # bring the feature in
git push
git branch -d feature/student-api    # delete the merged branch

git branch lists branches and marks the current one with *. (Older tutorials use git checkout -b and git checkout; git switch is the newer, clearer command.) Name branches after their purpose: feature/login, fix/email-validation.

On GitHub, teams usually merge through a pull request instead of merging locally: you push the branch, open a pull request, a teammate reviews the changes, then GitHub merges it. You'll practice this in lesson 14.

Resolving a merge conflict

If two branches change the same lines of a file, Git can't decide which version to keep, so the merge stops with a conflict:

$ git merge feature/new-title
Auto-merging index.html
CONFLICT (content): Merge conflict in index.html
Automatic merge failed; fix conflicts and then commit the result.

Git marks the conflict inside the file:

<h1>
<<<<<<< HEAD
Student Information System
=======
BISU Student Portal
>>>>>>> feature/new-title
</h1>
  • Between <<<<<<< HEAD and ======= is your current branch's version.
  • Between ======= and >>>>>>> is the incoming branch's version.

To resolve it:

  1. Edit the file to what it should be: keep one version, or combine them. Delete all three marker lines.
  2. Stage and commit:
git add index.html
git commit -m "Merge feature/new-title, keep the portal title"

VS Code highlights conflicts and offers buttons: Accept Current, Accept Incoming, Accept Both. To avoid conflicts in the first place, pull often, keep branches short-lived, and avoid having two people edit the same lines at the same time.

Quick check

After resolving a conflict in style.css, what's the next step?

Common mistakes

  • Forgetting await, so you get a Promise instead of the data.
  • Not checking response.ok, so a 404 is treated as success.
  • Sending JSON without the Content-Type: application/json header, or reading JSON from $_POST in PHP.
  • Returning 200 with {"error": ...}. Use the right status code.
  • Changing data with GET.
  • Single quotes or trailing commas in JSON.
  • Committing the conflict markers (<<<<<<<) into the file.

Summary

  • An API returns data (usually JSON) instead of pages, so any client can use it. REST uses URLs for things and methods for actions: GET reads, POST creates, PUT/PATCH update, DELETE removes.
  • Status codes tell clients what happened: 2xx success, 4xx client error, 5xx server error.
  • JSON.parse and JSON.stringify convert JSON; await fetch(url) makes a request, response.ok checks the status, and await response.json() reads the body.
  • A PHP endpoint sets Content-Type: application/json, sets a status code, and prints json_encode(...); it reads JSON input from php://input.
  • Git branches isolate work: git switch -c, git merge, and resolving conflicts by editing the marked lines, then add and commit.

That completes the midterm topics. Next comes modern front-end development: JavaScript modules and npm, then React and Next.js.

References and further reading