# JavaScript fetch bilan API'dan ma'lumot olish

> fetch bilan serverdan ma'lumot olish: GET va POST so'rovlari, response.json, status tekshirish va xatolarni boshqarish. Haqiqiy API misollari bilan.

Manba: https://learncode.uz/javascript/fetch/
Sana: 2026-06-02

Zamonaviy sahifa ma'lumotni serverdan **sahifani yangilamasdan** oladi:
mahsulotlar ro'yxati, ob-havo, izohlar. Buni `fetch` bajaradi.

## Birinchi so'rov

```js
async function fetchData() {
  const response = await fetch("https://api.github.com/repos/microsoft/vscode");
  const data = await response.json();

  console.log(data.name);
  console.log(data.stargazers_count);
}

fetchData();
```

Ikki qadam bor va ikkalasi ham `await` talab qiladi:

1. `fetch(...)` — so'rov yuboradi, **javob sarlavhalari** kelganda tugaydi;
2. `javob.json()` — javob tanasini o'qib, JavaScript obyektiga o'giradi.

> **Atama**
>
> **API** (Application Programming Interface) — dastur bilan gaplashish uchun
> manzil. Brauzer manzilga so'rov yuboradi, server ma'lumot qaytaradi — odatda
> [JSON](https://learncode.uz/javascript/json) shaklida. **fetch** — shu so'rovni yuboradigan
> brauzer funksiyasi; u [Promise](https://learncode.uz/javascript/promise) qaytaradi.

## Status tekshirish — muhim tuzoq

```js
async function fetchData() {
  const response = await fetch("https://api.github.com/repos/missing/missing-12345");

  console.log("ok:", response.ok);
  console.log("status:", response.status);
}

fetchData();
```

`404` keldi, lekin `fetch` **xato bermadi**. Bu ko'p uchraydigan yanglish
tushuncha: `fetch` faqat tarmoq uzilganda rad etiladi; server javob bersa —
hatto `404` yoki `500` bo'lsa ham — muvaffaqiyat hisoblanadi.

Shuning uchun `ok` ni qo'lda tekshirish kerak:

```js
async function fetchData(address) {
  const response = await fetch(address);

  if (!response.ok) {
    throw new Error("So'rov muvaffaqiyatsiz: " + response.status);
  }

  return response.json();
}

fetchData("https://api.github.com/repos/missing/missing-12345")
  .then((m) => console.log(m.name))
  .catch((e) => console.log("Xato:", e.message));
```

## try/catch bilan to'liq naqsh

```js
async function loadRepo(title) {
  try {
    const response = await fetch("https://api.github.com/repos/" + title);

    if (!response.ok) {
      throw new Error("Topilmadi (" + response.status + ")");
    }

    const m = await response.json();
    console.log(m.full_name, "—", m.stargazers_count, "yulduz");
  } catch (error) {
    console.log("Xatolik:", error.message);
  }
}

loadRepo("facebook/react");
loadRepo("bunday/repo-missing-99999");
```

Bu — amaliyotdagi standart naqsh: `try/catch` + `ok` tekshiruvi birga.

## Ro'yxat olish va chizish

```js
async function render() {
  const response = await fetch("https://api.github.com/users/torvalds/repos?per_page=5");
  const repos = await response.json();

  const ul = document.querySelector("#list");

  for (const repo of repos) {
    const li = document.createElement("li");
    li.textContent = repo.name + " (" + repo.language + ")";
    ul.append(li);
  }

  console.log("Chizildi:", repos.length, "ta");
}

render();
```

```html
<ul id="list"></ul>
```

Serverdan kelgan ma'lumot [DOM](https://learncode.uz/javascript/dom-ozgartirish) ga
aylantirildi — bu veb-ilovaning eng asosiy amali.

## POST — ma'lumot yuborish

Ma'lumot yuborish uchun qo'shimcha sozlamalar kerak:

```js
const response = await fetch("https://example.com/api/students", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ name: "Aziz", age: 20 }),
});

const result = await response.json();
```

Uch narsa muhim:

- `method` — so'rov turi (`GET` standart, `POST`, `PUT`, `DELETE`);
- `headers` — `Content-Type` server tanani qanday o'qishini aytadi;
- `body` — **matn** bo'lishi kerak, shuning uchun `JSON.stringify`.

> **body — obyekt emas, matn**
>
> `body: { ism: "Aziz" }` deb yozsangiz, server `[object Object]` oladi.
> Obyektni har doim `JSON.stringify` bilan matnga o'giring.

## Yuklanish holatini ko'rsatish

```js
const p = document.querySelector("#state");

async function fetchData() {
  p.textContent = "Yuklanmoqda...";

  try {
    const response = await fetch("https://api.github.com/repos/nodejs/node");
    if (!response.ok) throw new Error("Status " + response.status);

    const m = await response.json();
    p.textContent = m.full_name + " — " + m.stargazers_count + " yulduz";
  } catch (error) {
    p.textContent = "Xato: " + error.message;
  }
}

fetchData();
```

```html
<p id="state">—</p>
```

Uch holat — yuklanmoqda, natija, xato — har qanday ma'lumot oluvchi
interfeysning majburiy qismi.

## Parallel so'rovlar

```js
async function parallelRun() {
  const titles = ["vuejs/core", "sveltejs/svelte"];

  const responses = await Promise.all(
    titles.map((n) => fetch("https://api.github.com/repos/" + n))
  );

  const dataList = await Promise.all(responses.map((j) => j.json()));

  for (const m of dataList) {
    console.log(m.full_name, "—", m.stargazers_count);
  }
}

parallelRun();
```

Ikki `Promise.all`: birinchisi so'rovlarni, ikkinchisi tanalarni parallel
kutadi — [async/await](https://learncode.uz/javascript/async-await) darsidagi qoida.

## Amaliy mashq

1. GitHub API'dan istalgan repo ma'lumotini oling;
2. `javob.ok` ni tekshirib, xato bo'lsa `throw` qiling;
3. butun kodni `try/catch` ga o'rang;
4. kelgan ro'yxatni `<ul>` ichida chizing;
5. "Yuklanmoqda" holatini qo'shing;
6. mavjud bo'lmagan manzil so'rab, `fetch` xato bermasligini tasdiqlang.

6-qadam `fetch` haqidagi eng ko'p uchraydigan yanglishni tekshiradi.

## Qisqacha xulosa

- `fetch` so'rov yuboradi va Promise qaytaradi — `await` bilan ishlatiladi.
- Tanani o'qish alohida qadam: `await javob.json()`.
- `fetch` `404`/`500` da **xato bermaydi** — `javob.ok` ni qo'lda tekshiring.
- POST uchun `method`, `headers` va `JSON.stringify(body)` kerak.
- Yuklanmoqda / natija / xato — uchala holat ham ko'rsatilishi kerak.
- Bog'liq bo'lmagan so'rovlarni `Promise.all` bilan parallel yuboring.

Keyingi darsda [JSON](https://learncode.uz/javascript/json) formatini batafsil ko'ramiz.
