APIs and RESTful Services: Comprehensive Guide

APIs and RESTful Services: Comprehensive Guide

APIs (Application Programming Interfaces) and RESTful Services are crucial for building modern web applications. This guide introduces APIs, REST principles, HTTP methods, and how to interact with APIs using JavaScript. It includes examples, exercises, and multiple-choice questions.

What is an API?

An API is a set of rules that allows one application to communicate with another. APIs act as intermediaries between software systems.

What is a RESTful API?

A RESTful API adheres to the principles of REST (Representational State Transfer). It uses standard HTTP methods and operates on resources represented by URLs.

Key Characteristics:

  • Stateless: Each request is independent.
  • Client-Server: Clear separation of concerns.
  • Uniform Interface: Consistent operations (e.g., GET, POST, PUT, DELETE).

HTTP Methods

  • GET: Retrieve data from the server.
  • POST: Send data to the server to create a resource.
  • PUT: Update an existing resource.
  • DELETE: Remove a resource.

Example RESTful API:

Endpoint: https://jsonplaceholder.typicode.com/posts
Resource: Posts

Operations:

  • GET /posts: Retrieve all posts.
  • GET /posts/1: Retrieve a single post with ID 1.
  • POST /posts: Create a new post.
  • PUT /posts/1: Update post with ID 1.
  • DELETE /posts/1: Delete post with ID 1.

Using APIs with JavaScript

1. Fetch API

The fetch API is a modern JavaScript method for making HTTP requests.

Example: Fetching Data (GET Request)

fetch(“https://jsonplaceholder.typicode.com/posts”)

  .then((response) => response.json())

  .then((data) => console.log(data))

  .catch((error) => console.error(“Error:”, error));

Explanation:

  • fetch: Sends the HTTP request.
  • response.json(): Parses the response as JSON.
  • .then: Handles successful responses.
  • .catch: Handles errors.

Example: Sending Data (POST Request)

fetch(“https://jsonplaceholder.typicode.com/posts”, {

  method: “POST”,

  headers: {

    “Content-Type”: “application/json”

  },

  body: JSON.stringify({

    title: “New Post”,

    body: “This is a new post.”,

    userId: 1

  })

})

  .then((response) => response.json())

  .then((data) => console.log(data))

  .catch((error) => console.error(“Error:”, error));

Explanation:

  • method: Specifies the HTTP method (e.g., POST).
  • headers: Provides metadata (e.g., Content-Type).
  • body: Contains the data being sent (converted to JSON).

Common HTTP Status Codes

  • 200 OK: The request succeeded.
  • 201 Created: Resource created successfully.
  • 400 Bad Request: Invalid request.
  • 401 Unauthorized: Authentication required.
  • 404 Not Found: Resource not found.
  • 500 Internal Server Error: Server error.

Exercises

Exercise 1: Fetch and Display Data

Fetch posts from https://jsonplaceholder.typicode.com/posts and display the title of each post in the console.

Solution:

fetch(“https://jsonplaceholder.typicode.com/posts”)

  .then((response) => response.json())

  .then((data) => {

    data.forEach((post) => console.log(post.title));

  })

  .catch((error) => console.error(“Error:”, error));

Exercise 2: Submit a Form Using POST

Create a form that sends user input to https://jsonplaceholder.typicode.com/posts using a POST request.

Solution:

<form id=”postForm”>

  <input type=”text” id=”title” placeholder=”Title” required />

  <textarea id=”body” placeholder=”Content” required></textarea>

  <button type=”submit”>Submit</button>

</form>

<script>

  const form = document.getElementById(“postForm”);

  form.addEventListener(“submit”, (event) => {

    event.preventDefault();

    const title = document.getElementById(“title”).value;

    const body = document.getElementById(“body”).value;

    fetch(“https://jsonplaceholder.typicode.com/posts”, {

      method: “POST”,

      headers: {

        “Content-Type”: “application/json”

      },

      body: JSON.stringify({ title, body, userId: 1 })

    })

      .then((response) => response.json())

      .then((data) => console.log(“Post created:”, data))

      .catch((error) => console.error(“Error:”, error));

  });

</script>

Exercise 3: Handle Errors

Modify the fetch request to display an error message if the server returns an error.

Multiple-Choice Questions

Question 1:

Which HTTP method is used to update an existing resource?

  1. GET
  2. POST
  3. PUT
  4. DELETE

Answer: 3. PUT
Explanation: The PUT method updates an existing resource.

Question 2:

What is the purpose of the Content-Type header in an HTTP request?

  1. To specify the size of the request.
  2. To indicate the type of data being sent.
  3. To authenticate the request.
  4. None of the above.

Answer: 2. To indicate the type of data being sent.
Explanation: Content-Type specifies the format of the request body, such as application/json.

Question 3:

Which of the following is NOT a characteristic of a RESTful API?

  1. Statelessness
  2. Uniform Interface
  3. Tightly Coupled Client and Server
  4. Client-Server Architecture

Answer: 3. Tightly Coupled Client and Server
Explanation: RESTful APIs promote loose coupling between the client and server.

Advanced Example: Create a To-Do App Using an API

<!DOCTYPE html>

<html lang=”en”>

<head>

  <title>To-Do App</title>

</head>

<body>

  <h1>To-Do List</h1>

  <ul id=”todoList”></ul>

  <script>

    // Fetch and display to-do items

    fetch(“https://jsonplaceholder.typicode.com/todos?_limit=5”)

      .then((response) => response.json())

      .then((data) => {

        const todoList = document.getElementById(“todoList”);

        data.forEach((todo) => {

          const listItem = document.createElement(“li”);

          listItem.textContent = todo.title;

          if (todo.completed) {

            listItem.style.textDecoration = “line-through”;

          }

          todoList.appendChild(listItem);

        });

      })

      .catch((error) => console.error(“Error:”, error));

  </script>

</body>

</html>