DEV Community

Cover image for Learning FastAPI as a TypeScript Backend Developer: My Experience So Far
Subhamoy Datta
Subhamoy Datta

Posted on Edited on AI-assisted

Learning FastAPI as a TypeScript Backend Developer: My Experience So Far

I've been working with TypeScript and Node.js for a while, mainly building backend applications. Recently, I started exploring FastAPI while building a FastAPI-based AI full-stack project.

This wasn't my first experience with Python. I'd already used it in previous projects, so installing packages and managing dependencies wasn't much of an issue.

However, while building my first FastAPI-based project, I encountered several Python syntax patterns and libraries I hadn't worked with in my previous projects.

Some concepts felt familiar because of my TypeScript background, while others required more research and experimentation.

Here's what I've experienced so far.


1. Encountering Unfamiliar Python Syntax

Although I'd worked with Python before, I encountered several syntax patterns while implementing services that I hadn't used in my previous projects.

One example was:

(
    get_pkg_data(username, data.repo, data.path)
    for data in repo_pkg_data
)
Enter fullscreen mode Exit fullscreen mode

I already knew about generator functions, but I wasn't familiar with using generator expressions like this.

Initially, the syntax confused me.

After researching it, I understood that a generator expression produces values lazily instead of immediately creating a list.

In my case, I was working with asynchronous functions, so this pattern could be combined with asyncio.gather():

results = await asyncio.gather(
    *(
        get_pkg_data(username, data.repo, data.path)
        for data in repo_pkg_data
    )
)
Enter fullscreen mode Exit fullscreen mode

Here, the * unpacks the generated coroutine objects into separate arguments for asyncio.gather().

This was just one example. I encountered several unfamiliar syntax patterns and occasionally struggled with indentation while implementing services.

Instead of simply copying the code, I researched the syntax, experimented with it, and tried to understand how it worked internally.

2. asyncio.gather() vs Promise.all()

Interestingly, I didn't struggle with understanding asyncio.gather() because I'd already worked with Promise.all() in TypeScript.

TypeScript:

const [user, skills] = await Promise.all([
  getUser(username),
  getSkills(username),
]);
Enter fullscreen mode Exit fullscreen mode

Python:

user, skills = await asyncio.gather(
    get_user(username),
    get_skills(username)
)
Enter fullscreen mode Exit fullscreen mode

Both allow independent asynchronous operations to make progress concurrently and collect their results.

Although their error-handling and cancellation behavior differs, the underlying concurrency concept was familiar to me.

So understanding asyncio.gather() wasn't particularly difficult. I mainly needed to get comfortable with its Python syntax.

3. Python's Semaphore Implementation Surprised Me

One thing that genuinely surprised me was how simple semaphore usage was in Python.

In TypeScript, implementing a custom semaphore requires additional logic to manage concurrency limits, available permits, and waiting operations.

But Python already provides asyncio.Semaphore.

import asyncio

semaphore = asyncio.Semaphore(5)

async def fetch_with_limit():
    async with semaphore:
        return await fetch_data()
Enter fullscreen mode Exit fullscreen mode

Here, the semaphore allows up to five operations to hold permits concurrently when they share the same semaphore instance.

The async with block automatically acquires and releases a permit.

What surprised me wasn't the semaphore concept itself, but how little code Python required to use it.

Of course, TypeScript also has third-party libraries for concurrency control. My comparison was mainly with implementing a custom semaphore.

4. Pydantic vs Zod: Understanding Response Models

This was one of the more challenging parts of my FastAPI learning experience.

In my previous TypeScript backend projects, I used Zod for schema validation.

For example:

const UserSchema = z.object({
  username: z.string(),
  followers: z.number(),
  bio: z.string().nullable(),
});
Enter fullscreen mode Exit fullscreen mode

In FastAPI, I started working with Pydantic:

from pydantic import BaseModel

class UserSchema(BaseModel):
    username: str
    followers: int
    bio: str | None
Enter fullscreen mode Exit fullscreen mode

Both libraries support data validation, but their syntax and implementation differ.

My biggest challenge wasn't understanding schema validation itself. It was figuring out how to structure API responses and represent nested dictionaries and lists using Pydantic models.

Sometimes I wasn't sure whether a response should be represented as a dictionary, a list, or a combination of both.

Debugging Response Structures

To understand what my services were returning, I started logging the response data.

response = await client.get(url)

data = response.json()

print(data)
print(type(data))
Enter fullscreen mode Exit fullscreen mode

Based on the actual response structure, I defined the corresponding Pydantic model.

I also explored FastAPI's response_model:

@app.get("/users/{username}", response_model=UserSchema)
async def get_user_route(username: str):
    return await fetch_user(username)
Enter fullscreen mode Exit fullscreen mode

FastAPI uses the declared response model to validate and serialize the returned data.

If the returned data doesn't match the expected schema, FastAPI raises a response validation error.

This process helped me understand how Pydantic models relate to the data returned by my services.

5. SQLAlchemy vs Prisma: A Different ORM Experience

Another challenge came when I started using SQLAlchemy.

Previously, I'd worked with Prisma ORM, where defining database models felt straightforward.

For example:

model User {
  id    String @id @default(uuid())
  email String @unique
}
Enter fullscreen mode Exit fullscreen mode

But SQLAlchemy uses a different approach.

import uuid

from sqlalchemy import String, Uuid
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

class Base(DeclarativeBase):
    pass

class User(Base):
    __tablename__ = "users"

    id: Mapped[uuid.UUID] = mapped_column(
        Uuid,
        primary_key=True,
        default=uuid.uuid4
    )

    email: Mapped[str] = mapped_column(
        String,
        unique=True
    )
Enter fullscreen mode Exit fullscreen mode

When I first encountered Mapped, mapped_column(), and DeclarativeBase, their syntax confused me.

I had to research how they worked:

  • DeclarativeBase provides the base class for ORM models.
  • Mapped[T] provides a typed annotation for mapped attributes.
  • mapped_column() defines and configures database column mappings.

Another thing I had to understand was the difference between SQLAlchemy models and Pydantic schemas.

SQLAlchemy handles ORM/database mapping, while Pydantic handles data validation and serialization.

Coming from Prisma, adapting to this approach required some additional learning.

6. Python vs TypeScript: My Observations

One thing I've noticed throughout this experience is how concise Python can be.

Some operations that require more code when implemented manually in TypeScript can be accomplished with just a few lines using Python's built-in functionality.

The semaphore example was one of the clearest demonstrations of this.

However, fewer lines of code don't necessarily mean less complexity.

Sometimes Python felt simpler, while other times unfamiliar syntax and data structures made things confusing.

TypeScript also has its strengths, and because I've worked with it more extensively, many of its patterns feel more natural to me.

I don't think Python is better than TypeScript or vice versa.

Both languages have advantages and disadvantages, and working with FastAPI has helped me experience those differences firsthand.

Final Thoughts

Learning FastAPI has been an interesting experience.

Some concepts, like asyncio.gather(), were easy to understand because of my TypeScript background.

Others, particularly unfamiliar generator expressions, Pydantic response models, and SQLAlchemy's model-definition syntax, required more research and experimentation.

I'm still learning FastAPI, but one thing this experience has reinforced is the importance of understanding unfamiliar syntax and implementations rather than simply using them.

If you've moved from TypeScript or Node.js to FastAPI, what challenges or differences surprised you the most?

Top comments (0)