{}const=>[]async()letfn</>var
JSWeb

API processing in JavaScript and React: from basics to advanced level

Step-by-step guide to API processing in JavaScript and React. We analyze fetch, axios, work with API in components and TanStack Query. Suitable for beginners. Also learn about Kodik — a convenient application for learning programming from scratch.

К

Kodik

Author

3 min read

👋 Hello, front-enders!

Today we will analyze one of the most important topics in the world of JavaScript and React — working with the API. We will learn how to send HTTP requests, handle errors, and use popular libraries such as fetch, axios, and TanStack Query.

🔥 100,000+ students already with us

Tired of reading theory?
Time to code!

Kodik — an app where you learn to code through practice. AI mentor, interactive lessons, real projects.

🤖 AI 24/7
🎓 Certificates
💰 Free
🚀 Start learning
Joined today

📡 What is an API?

API (Application Programming Interface) is an interface through which programs exchange data with each other. For example, your React application can receive posts from a remote server via the API.

🛠️ APIs are often created using frameworks:

  • JavaScript — Express.js

  • Python — Django / Flask

  • Go — Gin

  • Java — Spring Boot

  • C# — ASP.NET Core


🔄 What is API processing?

API processing is the process of sending HTTP requests to the server and processing the received response. In JavaScript and React, the following are most often used:

  • fetch — built-in browser method

  • axios — a popular external library

  • TanStack Query (formerly React Query) — a library for easy management of asynchronous data in React


📬 Basic HTTP methods

Method

Purpose

GET

Data collection

POST

Sending new data

PUT

Complete resource update

PATCH

Partial update of the resource

DELETE

Deleting data from the server


⚙️ Working with the API through fetch

Simple GET request

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(res => res.json())
  .then(data => scrib.show(data))
  .catch(err => scrib.show('Error:', err));

POST request with body

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    title: 'JS is cool!',
    body: 'Scribbler allows you to combine HTML and JS',
    userId: 1
  })
})
  .then(res => res.json())
  .then(data => scrib.show(data))
  .catch(err => scrib.show('Error:', err));

Error handling via try/catch

async function getData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    if (!response.ok) throw new Error('Network error');
    const data = await response.json();
    scrib.show(data);
  } catch (err) {
    scrib.show('Error:', err);
  } finally {
    scrib.show('Request completed');
  }
}
getData();

⚡ Using axios

axios offers cleaner syntax and convenient error handling.

GET request

import axios from 'axios';

axios.get('https://jsonplaceholder.typicode.com/posts/1')
  .then(res => scrib.show(res.data))
  .catch(err => scrib.show('Error:', err));

POST request

axios.post('https://jsonplaceholder.typicode.com/posts', {
  title: 'Axios rules!',
  body: 'Error handling is much easier',
  userId: 1
}, {
  headers: { 'Content-Type': 'application/json' }
})
  .then(res => scrib.show(res.data))
  .catch(err => scrib.show('Error:', err));

Advanced error handling

axios.get('https://jsonpl.typicode.com/posts')
  .catch(error => {
    if (error.response) {
      scrib.show('Server error:', error.response.status);
    } else if (error.request) {
      scrib.show('No response from the server');
    } else {
      scrib.show('Request error:', error.message);
    }
  });

⚛️ API in React (useEffect + useState)

import { useEffect, useState } from 'react';

function Posts() {
  const [posts, setPosts] = useState([]);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(res => {
        if (!res.ok) throw new Error('Error retrieving data');
        return res.json();
      })
      .then(setPosts)
      .catch(err => setError(err.message));
  }, []);

  if (error) return <p>Ошибка: {error}</p>;

  return (
    <div>
      <h2>Посты</h2>
      <ul>{posts.map(p => <li key={p.id}>{p.title}</li>)}</ul>
    </div>
  );
}

⚙️ TanStack Query (React Query)

import { useQuery } from '@tanstack/react-query';
import axios from 'axios';

const fetchPosts = async () => {
  const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
  return data;
};

function Posts() {
  const { data: posts, error, isLoading } = useQuery({
    queryKey: ['posts'],
    queryFn: fetchPosts
  });

  if (isLoading) return <p>Загрузка...</p>;
  if (error) return <p>Ошибка: {error.message}</p>;

  return <ul>{posts.map(post => <li key={post.id}>{post.title}</li>)}</ul>;
}

✅ Conclusions

📌 API processing is a key skill in web development. The main thing:

  • Master fetch and axios

  • Understand HTTP methods

  • Be able to handle errors

  • Use useEffect in React

  • Automate data loading with TanStack Query

🎯Stop procrastinating

Liked the article?
Time to practice!

In Kodik, you don't just read — you write code immediately. Theory + practice = real skills.

Instant practice
🧠AI explains code
🏆Certificate

No registration • No card