Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is FastAPI and what are its advantages? FastAPI क्या है और इसके advantages क्या हैं?

Answer
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List

app = FastAPI()

# Request model
class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = False

class User(BaseModel):
    id: int
    username: str
    email: str

# GET request
@app.get('/')
async def read_root():
    return {'message': 'Hello World'}

# GET with parameter
@app.get('/items/{item_id}')
async def read_item(item_id: int):
    return {'item_id': item_id}

# GET with query parameter
@app.get('/users/')
async def read_users(skip: int = 0, limit: int = 10):
    return {'skip': skip, 'limit': limit}

# POST request
@app.post('/items/')
async def create_item(item: Item):
    return item

# PUT request
@app.put('/items/{item_id}')
async def update_item(item_id: int, item: Item):
    return {'item_id': item_id, 'item': item}

# DELETE request
@app.delete('/items/{item_id}')
async def delete_item(item_id: int):
    return {'deleted': item_id}

# Path and query parameters combined
@app.get('/users/{user_id}/items/{item_id}')
async def read_user_item(user_id: int, item_id: int, q: str = None):
    return {'user_id': user_id, 'item_id': item_id, 'q': q}

# Error handling
@app.get('/users/{user_id}')
async def read_user(user_id: int):
    if user_id < 1:
        raise HTTPException(status_code=400, detail='Invalid user ID')
    return {'user_id': user_id}

# Running: uvicorn main:app --reload
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.get('/')
async def read_root():
    return {'Hello': 'World'}

@app.post('/items/')
async def create_item(item: Item):
    return item

# Advantages:
# - Fast: High performance
# - Auto validation: Pydantic models
# - Auto docs: Swagger UI
# - Async/await: Async support
# - Type hints: Built-in type checking

Was this answer clear?