Skip to content

theMirmakhmudov/FastAPI-Learning

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 

Repository files navigation

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. 🚀

About

FastAPI docs for Learning by Mr.Mirmakhmudov coder

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages