API Consumption and Data Fetching

Professional Track: Complete this lesson with a working implementation, architecture notes, and a documented trade-off decision.

Overview

Reliable Vue applications treat API integration as a first-class architecture concern: contracts, retries, loading behavior, and failure states are designed upfront.

Fetch Architecture

Service + composable split

// services/usersApi.js
export async function listUsers(params) {
  const response = await fetch(`/api/users?page=${params.page}`)
  if (!response.ok) throw new Error('users_fetch_failed')
  return response.json()
}

// composables/useUsers.js
export function useUsers() {
  const users = ref([])
  const loading = ref(false)
  const error = ref('')
  return { users, loading, error }
}

Loading/success/error triad

Every async feature should define explicit render states so users never see ambiguous UI.

Resilience Patterns

Retries and timeout strategy

  • Retry idempotent GET requests with capped backoff.
  • Avoid blind retries for writes without idempotency keys.
  • Fail fast for unauthorized or invalid payload errors.

Optimistic update workflow

const previous = [...items.value]
items.value.unshift(newItem)
try {
  await api.createItem(newItem)
} catch (e) {
  items.value = previous
}

Contract Discipline

Typed DTO boundaries

Define request/response contracts near API services. Do not spread raw backend payload assumptions across components.

Error taxonomy

Map backend errors to user-facing categories: validation, authorization, conflict, and transient infrastructure failures.

Learning Objectives

  • Implement REST and GraphQL calls in composables.
  • Use optimistic updates when latency is high.
  • Design fallback UI for partial failures.

Common Mistakes

  • Scattering fetch calls directly inside multiple view components.
  • Assuming success shape and skipping response validation checks.
  • Showing generic "Something went wrong" without actionable recovery.

Engineering Notes

Document endpoint ownership, error semantics, and retry policies so frontend and backend teams share one integration language.

Practice Scope

Deliver one production-style mini-feature, include implementation notes, and record one performance, reliability, or maintainability trade-off in your commit summary.

Back to roadmap: Vue Roadmap