Api call

3 snippets across 3 stacks — Bash & Linux, JavaScript, React

Also written as API call

SHBash & Linux

Transfer Data with URLs

SH · Networking
syntax
curl [options] URL
example
curl https://api.example.com/users
curl -X POST -H 'Content-Type: application/json' -d '{"name":"Ada"}' https://api.example.com/users
curl -o release.tar.gz -L https://github.com/proj/repo/archive/v2.1.tar.gz

Note -o saves to a file, -O uses the remote filename. -L follows redirects (essential for GitHub downloads). -s silences progress bar. -I fetches only headers. -k skips TLS verification (use only for debugging, never in production).

JSJavaScript

Fetch API

JS · Async Programming
syntax
const response = await fetch(url, options);
example
// GET request
const res = await fetch("/api/products");
const products = await res.json();

// POST request
const created = await fetch("/api/products", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Widget", price: 29.99 }),
});

if (!created.ok) throw new Error(`HTTP ${created.status}`);

Note fetch() does NOT reject on HTTP error status codes (404, 500). Always check response.ok or response.status. The body can only be consumed once.

REReact

Fetching Data

RE · useEffect
syntax
useEffect(() => {
  let ignore = false;
  async function load() {
    const data = await fetchData();
    if (!ignore) setState(data);
  }
  load();
  return () => { ignore = true; };
}, [deps]);
example
function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let ignore = false;
    setLoading(true);

    async function loadUser() {
      const response = await fetch(`/api/users/${userId}`);
      const data = await response.json();
      if (!ignore) {
        setUser(data);
        setLoading(false);
      }
    }
    loadUser();

    return () => { ignore = true; };
  }, [userId]);

  if (loading) return <p>Loading...</p>;
  return <div>{user.name}</div>;
}

Note The ignore flag prevents setting state on an unmounted component or after a stale request. In React 19, consider using the use() hook with Suspense for data fetching instead of this pattern.