Online admissions open for the SEO, Web Development and Networking & Security courses. Enquire for the next batch.

What Is an API? REST, JSON and HTTP for Web Developers

3 min read Updated By the SkillNewton team

What is an API?

An API (Application Programming Interface) is a defined way for one program to request data or actions from another. On the web, most APIs work over HTTP: your code sends a request to a URL called an endpoint, and the server replies with a status code and data, usually in JSON. A REST API organises its endpoints around resources such as users or orders.

Anatomy of a request and a response

Every API call is an HTTP exchange. The request names a method and a path, carries headers and sometimes a body. The response carries a status code, headers and usually a body.

POST /api/v1/enquiries HTTP/1.1
Host: example.com
Content-Type: application/json
Authorization: Bearer <token>

{"name": "Meera", "course": "web-development"}

HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/v1/enquiries/314

{"id": 314, "name": "Meera", "status": "received"}

The client asked to create an enquiry, and the server confirmed with 201 Created, the URL of the new resource and a JSON copy of what it stored. JSON (JavaScript Object Notation) is plain text made of objects, arrays, strings, numbers, booleans and null, and every major language can read and write it.

HTTP methods and REST conventions

REST (Representational State Transfer) is a style rather than a strict standard. Its core idea is that URLs name resources, written as nouns, and HTTP methods describe what you want to do with them.

MethodPurposeExample
GETRead a resource or a listGET /api/v1/courses
POSTCreate a new resourcePOST /api/v1/enquiries
PUTReplace a resource completelyPUT /api/v1/users/7
PATCHUpdate part of a resourcePATCH /api/v1/users/7
DELETERemove a resourceDELETE /api/v1/users/7

GET requests must never change data, because browsers, caches and crawlers repeat them freely. Putting a version such as v1 in the path lets you change the API later without breaking existing clients.

Status codes you need to know

The status code tells the client what happened before it reads the body. The first digit gives the category: 2xx means success, 3xx a redirect, 4xx a problem with the request and 5xx a problem on the server.

CodeMeaning
200 OKThe request worked and the body holds the result
201 CreatedA new resource was created
204 No ContentSuccess with nothing to return, common after DELETE
400 Bad RequestThe request was malformed
401 UnauthorizedAuthentication is missing or invalid
403 ForbiddenAuthenticated, but not allowed to do this
404 Not FoundThe resource does not exist
422 Unprocessable ContentWell-formed, but the data failed validation
429 Too Many RequestsThe client exceeded a rate limit
500 Internal Server ErrorSomething failed on the server

Calling an API from JavaScript

In the browser you call APIs with fetch. This example sends JSON and handles both success and validation errors.

const res = await fetch('/api/v1/enquiries', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Meera', course: 'web-development' }),
});

if (res.status === 201) {
  const enquiry = await res.json();
  console.log('Saved with id', enquiry.id);
} else if (res.status === 422) {
  const { errors } = await res.json();
  console.warn(errors);
}

Our JavaScript guide shows how to attach this kind of call to a form and display the results safely on the page.

Building a simple JSON endpoint in PHP

On the server, an endpoint reads the request, validates it, does the work and returns JSON with the right status code.

<?php
declare(strict_types=1);
header('Content-Type: application/json');

$data = json_decode(file_get_contents('php://input'), true) ?? [];
$name = trim((string) ($data['name'] ?? ''));

if ($name === '') {
    http_response_code(422);
    echo json_encode(['errors' => ['name' => 'Name is required']]);
    exit;
}

$stmt = $pdo->prepare('INSERT INTO enquiries (name) VALUES (?)');
$stmt->execute([$name]);

http_response_code(201);
echo json_encode(['id' => (int) $pdo->lastInsertId(), 'name' => $name]);

The same rules from our PHP guide apply: validate input, and use prepared statements for every query. The data itself is saved in a MySQL table.

Authentication and security

  • Serve every API over HTTPS so tokens and data cannot be read in transit.
  • Keep secret API keys on the server. Anything in browser JavaScript is visible to every visitor, so call third-party APIs from your back end and pass on only the result.
  • Use tokens or session cookies to identify users, and check permissions on every request, not only at login.
  • Apply rate limits and return 429 when a client sends too many requests.
  • Configure CORS headers to allow only the origins that should call your API from a browser.

APIs connect everything else on this hub, from front-end scripts to databases. To practise them as part of complete projects, explore SkillNewton's online web development training.

Common mistakes

  • Returning 200 OK with an error message in the body, which forces clients to parse text to detect failures.
  • Using GET requests for actions that change or delete data.
  • Placing secret API keys in front-end JavaScript or committing them to a public code repository.
  • Trusting data from the request body without validating its type, length and format.
  • Returning raw database errors or stack traces in API responses.

Frequently asked questions

What is the difference between an API and a website?

A website returns HTML for people to read in a browser. An API returns structured data, usually JSON, for programs to use. Many sites do both: pages for visitors and an API that powers a mobile app or interactive features.

What is GraphQL?

GraphQL is an alternative to REST in which the client sends a query describing exactly which fields it wants, usually to a single endpoint. It reduces over-fetching for complex front ends but adds tooling and caching considerations, so REST remains a common starting point.

What is a webhook?

A webhook reverses the usual direction. Instead of your code asking another service for updates, that service sends an HTTP POST to a URL on your server when an event happens, such as a completed payment.

Do I need an API key for every API?

No. Some public APIs are open, but most require a key or token so the provider can identify callers, apply rate limits and protect private data.

Want to Learn This Properly?

The Online Web Development Course turns guides like this into practised skills, with projects on real websites.

WhatsApp Call Us Now