Skip to content
Mirmakhmudov Abdulmajid edited this page Mar 5, 2025 · 1 revision

image


(ENG) ๐Ÿš€ What Is FastAPI?

FastAPI is a modern, high-performance web framework for building APIs with Python based on standard type hints. It has the following key features:


๐ŸŒŸ Fast to run: It offers very high performance, on par with NodeJS and Go, thanks to Starlette and Pydantic.

โšก Fast to code: It allows for significant increases in development speed.

๐Ÿž Reduced number of bugs: It reduces the possibility for human-induced errors.

๐Ÿ–ฅ๏ธ Intuitive: It offers great editor support, with completion everywhere and less time debugging.

๐Ÿ“– Straightforward: Itโ€™s designed to be uncomplicated to use and learn, so you can spend less time reading documentation.

๐Ÿ“ Short: It minimizes code duplication.

๐Ÿ›ก๏ธ Robust: It provides production-ready code with automatic interactive documentation.

๐Ÿ“œ Standards-based: Itโ€™s based on the open standards for APIs, OpenAPI, and JSON Schema.


(UZ) ๐Ÿš€ FastAPI nima?

FastAPI - bu standart turdagi maslahatlar asosida Python bilan API yaratish uchun zamonaviy, yuqori samarali web-framework. U quyidagi asosiy xususiyatlarga ega:


โšก Tez ishga tushish: U Starlette va Pydantic tufayli NodeJS va Go bilan bir xilda juda yuqori unumdorlikni taklif etadi.

๐Ÿ’ป Tez kodlash: Bu rivojlanish tezligini sezilarli darajada oshirish imkonini beradi.

๐Ÿž Xatolar soni kamaytirildi: Bu inson tomonidan qo'zg'atilgan xatolar ehtimolini kamaytiradi.

๐Ÿ–ฅ๏ธ Intuitiv: U hamma joyda tugallangan va nosozliklarni tuzatishga kamroq vaqt sarflaydigan ajoyib muharrir yordamini taklif etadi.

๐Ÿ“– To'g'ridan-to'g'ri: Uni ishlatish va o'rganish oson bo'lishi uchun yaratilgan, shuning uchun hujjatlarni o'qishga kamroq vaqt sarflashingiz mumkin.

๐Ÿ“ Qisqa: Kodning takrorlanishini kamaytiradi.

๐Ÿ“œ Standartlarga asoslangan: U API, OpenAPI va JSON sxemasi uchun ochiq standartlarga asoslangan.


๐Ÿš€ Install FastAPI

๐Ÿ“Œ The first step is to install FastAPI and Uvicorn using pip:

python -m pip install fastapi uvicorn[standard]
pip install fastapi uvicorn[standard]

๐Ÿ First Step - Create a First API


๐Ÿ“Œ main.py

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

โ–ถ๏ธ Run the First API App With Uvicorn

๐Ÿ“Œ Run the live server using Uvicorn:


$ uvicorn main:app --reload

or

fastapi dev main.py

โœ… Check the Response

๐Ÿ“Œ Open your browser to http://127.0.0.1:8000, which will make your browser send a request to your application. It will then send a JSON response.


๐Ÿ“œ Check the Interactive API Documentation

๐Ÿ“Œ Now open http://127.0.0.1:8000/docs in your browser.


๐Ÿ“‘ Check the Alternative Interactive API Documentation

๐Ÿ“Œ Now, go to http://127.0.0.1:8000/redoc in your browser.


๐Ÿ”ฅ Important HTTP Methods (Muhim HTTP Methodlari)

Quyida keltirilgan yoโ€˜nalishlar mavjud:

  • GET: Ma'lumot olish
  • POST: Ma'lumot yuborish
  • PUT: Ma'lumotni yangilash
  • DELETE: Ma'lumotni o'chirish
  • PATCH: Ma'lumotni qisman yangilash

๐ŸŒŸ Example API Endpoints

from fastapi import FastAPI

app = FastAPI()

data = []

@app.get("/items")
def get_items():
    return {"items": data}

@app.post("/items")
def create_item(item: dict):
    data.append(item)
    return {"message": "Item added", "item": item}

@app.delete("/items/{item_id}")
def delete_item(item_id: int):
    if 0 <= item_id < len(data):
        deleted_item = data.pop(item_id)
        return {"message": "Item deleted", "item": deleted_item}
    return {"error": "Item not found"}

@app.patch("/items/{item_id}")
def update_item(item_id: int, item: dict):
    if 0 <= item_id < len(data):
        data[item_id].update(item)
        return {"message": "Item updated", "item": data[item_id]}
    return {"error": "Item not found"}

๐Ÿ—„๏ธ Database Connection Example

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

class Item(Base):
    __tablename__ = "items"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)

Base.metadata.create_all(bind=engine)

๐Ÿ”„ Concurrency vs Parallelism

๐Ÿ”น Concurrency allows multiple tasks to make progress without necessarily running simultaneously. ๐Ÿ”น Parallelism executes multiple tasks at the exact same time using multiple processors.

Example:

import asyncio

async def task(name, delay):
    await asyncio.sleep(delay)
    print(f"Task {name} completed")

async def main():
    await asyncio.gather(task("A", 2), task("B", 1))

asyncio.run(main())

image image image image image image image


image image image image image image


๐ŸŽฏ Xulosa (Conclusion)

FastAPI - bu yuqori samarali va kuchli API yaratish uchun moโ€˜ljallangan framework. U oddiy ishlash, avtomatik hujjatlashtirish va yuqori tezlikni taโ€™minlaydi. ๐Ÿš€