Тест на вакансию

Создание REST API на FastAPI (Python) с Bearer авторизацией и управлением статьями

10 сентября 2025 г.
280

Установка зависимостей

Создаём новое приложение:
mkdir fastapi-articles-api
cd fastapi-articles-api
Устанавливаем зависимости:
pip install fastapi uvicorn python-jose[cryptography] passlib[bcrypt] python-multipart pydantic[email] asyncpg

Структура проекта

Первоначальная структура проекта приложения должна выглядеть так:
  • fastapi-articles-api/
    • main.py
    • models.py
    • auth.py
    • database.py
    • config.py
    • requirements.txt
    • .env

Установка зависимостей

Отредактируем файл (requirements.txt):
fastapi==0.104.1
uvicorn[standard]==0.24.0
python-jose[cryptography]==3.3.0
passlib[bcrypt]==1.7.4
python-multipart==0.0.6
sqlalchemy==2.0.23
asyncpg==0.29.0
psycopg2-binary==2.9.9
pydantic==2.5.0
pydantic-settings==2.1.0
python-dotenv==1.0.0
alembic==1.12.1

Установка зависимостей:
pip install -r requirements.txt

Файл .env

Отредактируем файл (.env):
# Database
DATABASE_URL=postgresql://username:password@localhost:5432/article_db
DATABASE_SSL=false
# JWT
SECRET_KEY=your-super-secret-jwt-key-change-this-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
# App
DEBUG=true
HOST=0.0.0.0
PORT=8000

Базовые модели (models.py)

from pydantic import BaseModel, EmailStr
from typing import List, Optional
from datetime import datetime

class UserBase(BaseModel):
    username: str
    email: EmailStr

class UserCreate(UserBase):
    password: str

class User(UserBase):
    id: int
    is_active: bool
    created_at: datetime
    updated_at: datetime
    class Config:
        from_attributes = True

class ArticleBase(BaseModel):
    title: str
    content: str
    is_published: bool = False

class ArticleCreate(ArticleBase):
    pass

class Article(ArticleBase):
    id: int
    author_id: int
    created_at: datetime
    updated_at: datetime
    class Config:
        from_attributes = True

class Token(BaseModel):
    access_token: str
    token_type: str
    expires_in: Optional[int] = None

class TokenData(BaseModel):
    username: Optional[str] = None

class UserResponse(BaseModel):
    id: int
    username: str
    email: EmailStr
    is_active: bool
    created_at: datetime

class ArticleResponse(Article):
    author: UserResponse

class UserResponse(BaseModel):
    id: int
    username: str
    email: EmailStr
    is_active: bool
    created_at: datetime
    updated_at: datetime
    class Config:
        from_attributes = True

class ArticleResponse(ArticleBase):
    id: int
    author_id: int
    created_at: datetime
    updated_at: datetime
    class Config:
        from_attributes = True

class ArticleWithAuthorResponse(ArticleResponse):
    author: UserResponse

Настройка аутентификации (auth.py)

from datetime import datetime, timedelta
from jose import JWTError, jwt
from passlib.context import CryptContext
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from typing import Optional, AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select

from config import settings
from database import get_db, User
from models import TokenData

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

def verify_password(plain_password: str, hashed_password: str) -> bool:
    return pwd_context.verify(plain_password, hashed_password)

def get_password_hash(password: str) -> str:
    return pwd_context.hash(password)

async def get_user(db: AsyncSession, username: str) -> Optional[User]:
    result = await db.execute(select(User).filter(User.username == username))
    return result.scalar_one_or_none()

async def authenticate_user(
    db: AsyncSession,
    username: str,
    password: str
) -> Optional[User]:
    user = await get_user(db, username)
    if not user:
        return None
    if not verify_password(password, user.hashed_password):
        return None
    return user

def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
   
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
   
    return encoded_jwt

async def get_current_user(
    token: str = Depends(oauth2_scheme),
    db: AsyncSession = Depends(get_db)
) -> User:
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
   
    try:
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_data = TokenData(username=username)
    except JWTError:
        raise credentials_exception
   
    user = await get_user(db, username=token_data.username)
    if user is None:
        raise credentials_exception
    return user

async def get_current_active_user(
    current_user: User = Depends(get_current_user)
) -> User:
    if not current_user.is_active:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Inactive user"
        )
    return current_user

async def create_user(
    db: AsyncSession,
    username: str,
    email: str,
    password: str
) -> User:
    existing_user = await get_user(db, username)
    if existing_user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Username already registered"
        )
   
    new_user = User(
        username=username,
        email=email,
        hashed_password=get_password_hash(password),
        is_active=True
    )
   
    db.add(new_user)
    await db.commit()
    await db.refresh(new_user)
   
    return new_user

Основное приложение (main.py)

from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from typing import List
from datetime import datetime, timedelta
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from sqlalchemy.orm import selectinload

from config import settings
from auth import (
    get_current_active_user,
    authenticate_user,
    create_access_token,
    create_user
)
from models import User, ArticleCreate, Token, UserCreate, ArticleResponse, ArticleWithAuthorResponse
from database import get_db, create_tables, init_data, User as DBUser, Article as DBArticle

app = FastAPI(
    title="Article API with PostgreSQL",
    version="1.0.0",
    debug=settings.DEBUG
)

@app.on_event("startup")
async def startup_event():
    await create_tables()
    await init_data()

@app.post("/token", response_model=Token)
async def login_for_access_token(
    form_data: OAuth2PasswordRequestForm = Depends(),
    db: AsyncSession = Depends(get_db)
):
    user = await authenticate_user(db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
   
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username},
        expires_delta=access_token_expires
    )
   
    expires_in = int(access_token_expires.total_seconds())
   
    return {
        "access_token": access_token,
        "token_type": "bearer",
        "expires_in": expires_in
    }

@app.post("/register", response_model=User)
async def register_user(
    user_data: UserCreate,
    db: AsyncSession = Depends(get_db)
):
    return await create_user(db, user_data.username, user_data.email, user_data.password)

@app.get("/articles", response_model=List[ArticleResponse])
async def read_articles(
    skip: int = 0,
    limit: int = 10,
    published_only: bool = False,
    db: AsyncSession = Depends(get_db)
):
    query = select(DBArticle)
    if published_only:
        query = query.where(DBArticle.is_published == True)
   
    query = query.offset(skip).limit(limit)
   
    result = await db.execute(query)
    articles = result.scalars().all()
   
    return articles

@app.get("/articles/{article_id}", response_model=ArticleResponse)
async def read_article(
    article_id: int,
    db: AsyncSession = Depends(get_db)
):
    query = select(DBArticle).where(DBArticle.id == article_id)
    result = await db.execute(query)
    article = result.scalar_one_or_none()
   
    if article is None:
        raise HTTPException(status_code=404, detail="Article not found")
   
    return article

@app.get("/articles/{article_id}/full", response_model=ArticleWithAuthorResponse)
async def read_article_full(
    article_id: int,
    db: AsyncSession = Depends(get_db)
):
    query = select(DBArticle).options(selectinload(DBArticle.author)).where(DBArticle.id == article_id)
    result = await db.execute(query)
    article = result.scalar_one_or_none()
   
    if article is None:
        raise HTTPException(status_code=404, detail="Article not found")
   
    return article

@app.post("/articles", response_model=ArticleResponse)
async def create_article(
    article: ArticleCreate,
    current_user: DBUser = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    db_article = DBArticle(
        title=article.title,
        content=article.content,
        is_published=article.is_published,
        author_id=current_user.id,
        created_at=datetime.utcnow(),
        updated_at=datetime.utcnow()
    )
   
    db.add(db_article)
    await db.commit()
    await db.refresh(db_article)
   
    return db_article

@app.put("/articles/{article_id}", response_model=ArticleResponse)
async def update_article(
    article_id: int,
    article: ArticleCreate,
    current_user: DBUser = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    query = select(DBArticle).where(DBArticle.id == article_id)
    result = await db.execute(query)
    db_article = result.scalar_one_or_none()
   
    if db_article is None:
        raise HTTPException(status_code=404, detail="Article not found")
   
    if db_article.author_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not enough permissions")
   
    db_article.title = article.title
    db_article.content = article.content
    db_article.is_published = article.is_published
    db_article.updated_at = datetime.utcnow()
   
    await db.commit()
    await db.refresh(db_article)
   
    return db_article

@app.delete("/articles/{article_id}")
async def delete_article(
    article_id: int,
    current_user: DBUser = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    query = select(DBArticle).where(DBArticle.id == article_id)
    result = await db.execute(query)
    db_article = result.scalar_one_or_none()
   
    if db_article is None:
        raise HTTPException(status_code=404, detail="Article not found")
   
    if db_article.author_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not enough permissions")
   
    await db.delete(db_article)
    await db.commit()
   
    return {"message": "Article deleted successfully"}

@app.get("/users/me", response_model=User)
async def read_users_me(current_user: DBUser = Depends(get_current_active_user)):
    return current_user

@app.get("/users/{user_id}/articles", response_model=List[ArticleResponse])
async def read_user_articles(
    user_id: int,
    skip: int = 0,
    limit: int = 10,
    published_only: bool = False,
    db: AsyncSession = Depends(get_db)
):
    query = select(DBArticle).where(DBArticle.author_id == user_id)
   
    if published_only:
        query = query.where(DBArticle.is_published == True)
   
    query = query.offset(skip).limit(limit)
   
    result = await db.execute(query)
    articles = result.scalars().all()
   
    return articles
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        app,
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.DEBUG
    )

database.py

from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.future import select
from datetime import datetime
from typing import AsyncGenerator

import ssl

from config import settings

ssl_context = None
if settings.DATABASE_SSL:
    ssl_context = ssl.create_default_context()

engine = create_async_engine(
    settings.DATABASE_URL,
    echo=settings.DEBUG,
    connect_args={"ssl": ssl_context} if settings.DATABASE_SSL else {}
)

AsyncSessionLocal = sessionmaker(
    engine,
    class_=AsyncSession,
    expire_on_commit=False,
    autocommit=False,
    autoflush=False,
)

Base = declarative_base()

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String, unique=True, index=True, nullable=False)
    email = Column(String, unique=True, index=True, nullable=False)
    hashed_password = Column(String, nullable=False)
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    articles = relationship("Article", back_populates="author", cascade="all, delete-orphan")

class Article(Base):
    __tablename__ = "articles"

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True, nullable=False)
    content = Column(String, nullable=False)
    is_published = Column(Boolean, default=False)
    author_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    author = relationship("User", back_populates="articles")

async def get_db() -> AsyncGenerator[AsyncSession, None]:
    async with AsyncSessionLocal() as session:
        try:
            yield session
        finally:
            await session.close()

async def create_tables():
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

async def init_data():
    async with AsyncSessionLocal() as db:
        from auth import get_password_hash
        
        result = await db.execute(select(User).filter(User.username == "admin"))
        existing_user = result.scalar_one_or_none()
        
        if not existing_user:
            admin_user = User(
                username="admin",
                email="admin@example.com",
                hashed_password=get_password_hash("adminpassword"),
                is_active=True
            )
            db.add(admin_user)
            await db.commit()
            await db.refresh(admin_user)
            
            test_article = Article(
                title="Добро пожаловать в Article API",
                content="Это ваша первая статья. Вы можете ее отредактировать или удалить.",
                is_published=True,
                author_id=admin_user.id
            )
            db.add(test_article)
            await db.commit()
            
            print("Initial data created successfully")

config.py

from pydantic_settings import BaseSettings
from typing import Optional

class Settings(BaseSettings):
    # Database
    DATABASE_URL: str
    DATABASE_SSL: bool = False
   
    # JWT
    SECRET_KEY: str
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
   
    # App
    DEBUG: bool = False
    HOST: str = "0.0.0.0"
    PORT: int = 8000
   
    class Config:
        env_file = ".env"

settings = Settings()

Тестирование

Запуск сервера:
uvicorn main:app --reload --host 0.0.0.0 --port 8000
Получение токена:
curl -X POST "http://localhost:8000/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=admin&password=adminpassword"
Создание статьи:
curl -X POST "http://localhost:8000/articles" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Моя первая статья",
    "content": "Содержание статьи...",
    "is_published": true
  }'
Получение статей:
curl -X GET "http://localhost:8000/articles" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Обновление статьи:
curl -X PUT "http://localhost:8000/articles/1" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Обновленный заголовок",
    "content": "Обновленное содержание",
    "is_published": false
  }'
Удаление статьи:
curl -X DELETE "http://localhost:8000/articles/1" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Посмотреть документацию:
curl -X GET "http://localhost:8000/docs"
Посмотреть все routes:
curl -X GET "http://localhost:8000/openapi.json"
 
Поделиться: