Learning About API's

Learning About API's

An API, or Application Programming Interface, is like a set of rules that allows different software applications to communicate with each other. It defines the methods and data formats that developers can use to interact with a particular software service or platform. Essentially, it acts as a bridge that enables different programs to work together seamlessly.

Let's say you are creating a IMDB Clone

  • Its easy to make the routings,layouts, authentications

  • But How are you going to display all the movies and their details

  • Are u going to hard code them?

  • Absolutely not ! This is where API comes in the picture

  • API has the data from the source we just have to arrange the systematically way so that we can arrange those datas in a manner or a ordered way

Let's Learn How to create a API

Following are the most commonly used API

  1. REST API

  2. GRAPH QL

  3. WEB SOCKETS

Representational State Transfer API

  1. GET:-

Used to retrieve resource representations or collections of resources from the server. GET requests should not have any side effects on the server and are considered safe and idempotent, meaning multiple identical requests should have the same effect as a single request.

const express = require('express');
const app = express();

// Sample data
const books = [
  { id: 1, title: 'Book 1', author: 'Author 1' },
  { id: 2, title: 'Book 2', author: 'Author 2' },
  { id: 3, title: 'Book 3', author: 'Author 3' }
];

// Define a route to handle GET requests to /books
app.get('/books', (req, res) => {
  res.json(books); // Return the array of books as JSON response
});

// Start the server
const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});
  1. POST

Used to create new resources on the server. POST requests typically include a payload containing the data for the new resource, which is then processed and stored by the server. Unlike GET requests, POST requests can have side effects on the server and are not idempotent.

const express = require('express');
const bodyParser = require('body-parser'); // Required to parse request bodies
const app = express();

// Middleware to parse JSON bodies
app.use(bodyParser.json());

// Sample data (initially empty)
let users = [];

// Define a route to handle POST requests to /users
app.post('/users', (req, res) => {
  // Extract the user data from the request body
  const { name, email } = req.body;

  // Create a new user object
  const newUser = { id: users.length + 1, name, email };

  // Add the new user to the users array
  users.push(newUser);

  // Send a JSON response with the newly created user
  res.json(newUser);
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});
  1. PUT
    Used to update existing resources on the server or create a new resource if it doesn't exist. PUT requests typically include a payload containing the updated data for the resource, which is then stored or replaced by the server. PUT requests are idempotent, meaning multiple identical requests should have the same effect as a single request.
const express = require('express');
const bodyParser = require('body-parser'); // Required to parse request bodies
const app = express();

// Middleware to parse JSON bodies
app.use(bodyParser.json());

// Sample data (initially empty)
let users = [];

// Define a route to handle PUT requests to /users/:id
app.put('/users/:id', (req, res) => {
  // Extract the user ID from the request parameters
  const userId = parseInt(req.params.id);

  // Extract the updated user data from the request body
  const { name, email } = req.body;

  // Find the user in the users array by ID
  const user = users.find(user => user.id === userId);

  // If user is not found, return 404 Not Found
  if (!user) {
    return res.status(404).json({ error: 'User not found' });
  }

  // Update the user data
  user.name = name || user.name;
  user.email = email || user.email;

  // Send a JSON response with the updated user
  res.json(user);
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});
  1. PATCH
    Similar to PUT, PATCH is used to update existing resources on the server. However, PATCH requests only include the data that needs to be updated, rather than the entire resource representation. This makes PATCH requests more efficient when only a subset of the resource needs to be modified.
const express = require('express');
const bodyParser = require('body-parser'); // Required to parse request bodies
const app = express();

// Middleware to parse JSON bodies
app.use(bodyParser.json());

// Sample data (initially empty)
let users = [];

// Define a route to handle PATCH requests to /users/:id
app.patch('/users/:id', (req, res) => {
  // Extract the user ID from the request parameters
  const userId = parseInt(req.params.id);

  // Extract the updated user data from the request body
  const { name, email } = req.body;

  // Find the user in the users array by ID
  const user = users.find(user => user.id === userId);

  // If user is not found, return 404 Not Found
  if (!user) {
    return res.status(404).json({ error: 'User not found' });
  }

  // Update the user data if provided in the request body
  if (name) {
    user.name = name;
  }
  if (email) {
    user.email = email;
  }

  // Send a JSON response with the updated user
  res.json(user);
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});
  1. DELETE

Used to remove resources from the server. DELETE requests typically specify the resource to be deleted in the request URL, and the server then removes the corresponding resource. DELETE requests are idempotent, meaning multiple identical requests should have the same effect as a single request.

const express = require('express');
const app = express();

// Sample data (initially empty)
let users = [];

// Define a route to handle DELETE requests to /users/:id
app.delete('/users/:id', (req, res) => {
  // Extract the user ID from the request parameters
  const userId = parseInt(req.params.id);

  // Find the index of the user in the users array by ID
  const userIndex = users.findIndex(user => user.id === userId);

  // If user is not found, return 404 Not Found
  if (userIndex === -1) {
    return res.status(404).json({ error: 'User not found' });
  }

  // Remove the user from the users array
  users.splice(userIndex, 1);

  // Send a JSON response indicating successful deletion
  res.json({ message: 'User deleted successfully' });
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Let's Fetch Github Users API and display it in React

import React, { useState } from 'react';

function App() {
  const [query, setQuery] = useState('');
  const [users, setUsers] = useState([]);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  const fetchUsers = async () => {
    setLoading(true);
    setError(null);

    try {
      const response = await fetch(`https://api.github.com/search/users?q=${query}`);
      const data = await response.json();
      setUsers(data.items);
    } catch (error) {
      setError('Error fetching data');
    }

    setLoading(false);
  };

  const handleChange = (event) => {
    setQuery(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    fetchUsers();
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input type="text" value={query} onChange={handleChange} />
        <button type="submit">Search</button>
      </form>

      {loading && <p>Loading...</p>}
      {error && <p>{error}</p>}
      {users.length > 0 && (
        <ul>
          {users.map((user) => (
            <li key={user.id}>{user.login}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

export default App;

Did you find this article valuable?

Support Thirumalai by becoming a sponsor. Any amount is appreciated!