React Tutorial 0/120 lessons ~6 min read Lesson 52

    API Integration Basics

    API Integration Basics covers the request lifecycle, REST conventions, HTTP status codes, frontend service layers, contracts, and CORS.

    Course progress0%
    Focus
    11 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Course: React — Routing & API Integration Lesson: 07

    Learning objectives

    Understand the browser-to-backend request lifecycle, REST resource conventions, HTTP methods and status codes, JSON payloads, and the role of a frontend service layer.

    What API integration means

    A React UI rarely owns all application data. In a SaaS product, customers, orders, invoices, subscriptions, and permissions usually live on backend services. API integration connects the UI to those systems.

    text
    React Component
    |
    v
    Feature Hook / Data Layer
    |
    v
    API Service
    |
    v
    HTTP Request
    |
    v
    Backend API -> Database / Services
    |
    v
    JSON Response -> UI State -> Render

    The component should focus on what the user sees. The service should own HTTP details such as endpoint paths, headers, and response parsing.

    REST-style resources

    Typical resource endpoints:

    • GET /api/orders — retrieve orders.
    • GET /api/orders/123 — retrieve one order.
    • POST /api/orders — create an order.
    • PUT /api/orders/123 — replace a resource representation.
    • PATCH /api/orders/123 — partially update a resource.
    • DELETE /api/orders/123 — delete a resource.

    The exact contract is defined by the backend. Do not infer request fields or response structures without checking the API specification.

    HTTP status codes

    Common responses include:

    • 200 OK: request succeeded.
    • 201 Created: resource created.
    • 204 No Content: succeeded with no response body.
    • 400 Bad Request: invalid request.
    • 401 Unauthorized: authentication is missing or invalid.
    • 403 Forbidden: caller is authenticated but not allowed.
    • 404 Not Found: resource or endpoint not found.
    • 409 Conflict: request conflicts with current resource state.
    • 422 Unprocessable Content: validation or semantic error, depending on API contract.
    • 429 Too Many Requests: rate limit reached.
    • 5xx: server-side failure.

    A frontend should translate technical failures into clear, actionable messages without exposing secrets or internal stack traces.

    Create an API service

    javascript
    const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
    export async function getOrders({ signal } = {}) {
    const response = await fetch(`${API_BASE_URL}/orders`, {
    headers: { Accept: "application/json" },
    signal
    });
    if (!response.ok) {
    throw new Error(`Orders request failed: ${response.status}`);
    }
    return response.json();
    }

    Keep environment-specific configuration outside source code. Client-side environment variables are visible to users after bundling; never put private API keys or server secrets in them.

    Request and response contracts

    Document expected request fields, response fields, validation errors, pagination shape, and authentication requirements. Use TypeScript types or runtime schema validation where appropriate. A frontend type declaration does not validate untrusted network data at runtime.

    CORS and environments

    A browser may block a cross-origin request unless the backend allows the frontend origin through CORS policy. Configure CORS on the server or gateway. Do not treat a frontend workaround as a substitute for correct server configuration.

    Common mistakes

    • Assuming fetch rejects for HTTP 404 or 500 responses.
    • Hard-coding production URLs.
    • Exposing secrets in frontend environment variables.
    • Mixing HTTP code into every visual component.
    • Ignoring response contracts and validation errors.
    • Treating CORS as a React bug.

    Best practices

    Centralize API configuration, define clear service functions, handle non-2xx responses, use cancellation for obsolete requests, and document API contracts.

    Interview questions & answers

    Interview preparation

    5 questions grouped by difficulty — expand any card for a model answer and follow-up probe.

    Beginner

    2
    1. 1Explain the lifecycle of a React API request.
      Beginner

      Model answer

      UI intent flows through a feature hook or data layer into an API service, then an HTTP request to the backend; the JSON response updates UI state and re-renders.

    2. 2What is CORS?
      Beginner

      Model answer

      Cross-Origin Resource Sharing is a browser security policy.

      The backend or gateway must allow the frontend origin; CORS is not a React bug to patch on the client alone.

    Intermediate

    2
    1. 3What is the difference between 401 and 403?
      Intermediate

      Model answer

      401 means authentication is missing or invalid. 403 means the caller is authenticated but not allowed to perform the action.
    2. 4Why should API calls be separated from presentation components?
      Intermediate

      Model answer

      A service layer owns endpoints, headers, and parsing so components stay focused on UI state and presentation, improving reuse and testability.

    Advanced

    1
    1. 5Does fetch reject on HTTP 404?
      Advanced

      Model answer

      No. fetch resolves with a Response; you must check response.ok or status and throw or handle non-2xx results yourself.

    Practice

    Implement list, detail, create, and update service functions for an order resource. Use a mock API contract and handle success, validation, and server-error responses.

    Ready to mark this lesson complete?Track your journey across the entire course.