FastAPI बैकएंड डेवलपमेंट बूटकैंप · पाठ

प्रकार, क्वेरी और म्यूटेशन निर्धारित करना

Strawberry के साथ टाइपयुक्त GraphQL स्कीमा बनाइए और साझा निर्भरताओं के साथ उसे FastAPI ऐप पर स्थापित कीजिए।

पाठ 1, कुल 4 में से13 चरण

प्रकार, क्वेरी और म्यूटेशन निर्धारित करना, CoddyKit पर FastAPI बैकएंड डेवलपमेंट बूटकैंप का एक निःशुल्क पाठ है। यह 4 में से 1वाँ पाठ है। इस अध्ययन पथ के 3 तक कोई भी पाठ पूरा पढ़ना निःशुल्क है — इसके बाद CoddyKit PRO हर पाठ अनलॉक करता है, साथ ही अंतर्निर्मित कोड संपादक और चौबीसों घंटे एआई शिक्षक के साथ व्यावहारिक अभ्यास भी उपलब्ध कराता है। यह FastAPI बैकएंड डेवलपमेंट बूटकैंप सीखने के मार्ग का हिस्सा है और आपकी प्रगति वेब तथा CoddyKit ऐप पर सिंक होती रहती है। FastAPI बैकएंड डेवलपमेंट बूटकैंप पाठ्यक्रम में कुल 4 पाठ शामिल हैं।

FastAPI पर GraphQL के लिए Strawberry क्यों

Strawberry Python की एक code-first GraphQL library है, जो आपका schema परिभाषित करने के लिए dataclasses और type hints का उपयोग करती है। GraphQL SDL हाथ से लिखने के बजाय, आप सामान्य Python classes लिखते हैं और Strawberry उनसे schema तैयार करती है।

  • Code-first: Python types ही सत्य का मूल स्रोत हैं — SDL generate होता है।
  • Type-safe: मानक type hints (int, str, list[str], Optional) सीधे GraphQL types में बदलते हैं।
  • ASGI-native: यह ऐसा router देती है जिसे FastAPI app पर आसानी से mount किया जा सकता है और जो उसके event loop तथा dependency system को साझा करता है।

इस lesson में हम एक typed schema (types, एक Query और एक Mutation) बनाएँगे और shared dependencies के साथ उसे FastAPI पर mount करेंगे।

Object Type परिभाषित करना

GraphQL का object type केवल @strawberry.type से सजाई गई एक class है। प्रत्येक annotated attribute एक field बन जाता है। Type hints GraphQL field type निर्धारित करते हैं: int से Int, str से String, और non-optional field से non-null (!) बनता है।

  • Identifier fields के लिए strawberry.ID इस्तेमाल करें — यह string के रूप में serialize होता है, लेकिन identity semantics दर्शाता है।
  • Optional[...] (या X | None) किसी field को nullable बनाता है।
import strawberry
from typing import Optional


@strawberry.type
class Book:
    id: strawberry.ID
    title: str
    author: str
    pages: int
    summary: Optional[str] = None

Query Root Type

हर GraphQL schema को एक Query root की आवश्यकता होती है — यही reads का entry point है। इसे @strawberry.type के रूप में घोषित किया जाता है, जिसके fields @strawberry.field से सजाई गई methods द्वारा resolve किए जाते हैं।

  • Method का return annotation उसके GraphQL type को परिभाषित करता है।
  • self के अलावा method parameters, GraphQL arguments बन जाते हैं।
  • list[Book] लौटाने पर non-null books की non-null list बनती है: [Book!]!।
import strawberry


@strawberry.type
class Query:
    @strawberry.field
    def books(self) -> list[Book]:
        return [
            Book(id="1", title="Dune", author="Herbert", pages=412),
            Book(id="2", title="1984", author="Orwell", pages=328),
        ]

    @strawberry.field
    def book(self, id: strawberry.ID) -> Book | None:
        for b in self.books():
            if b.id == id:
                return b
        return None

Schema बनाना

strawberry.Schema root types को आपस में जोड़ता है। कम-से-कम आपको query=Query देना होता है; बाद में आप mutation=Mutation जोड़ सकते हैं। Schema बनाने पर आपके types validate होते हैं और आप generate किया गया SDL print कर सकते हैं — यह sanity check के लिए बहुत उपयोगी है।

यहाँ एक पूरी तरह standalone उदाहरण है: एक type और एक query परिभाषित करें, schema बनाएँ और schema.execute_sync के साथ query को synchronously execute करें। किसी server या framework की आवश्यकता नहीं है।

import strawberry


@strawberry.type
class Book:
    id: strawberry.ID
    title: str
    author: str


@strawberry.type
class Query:
    @strawberry.field
    def books(self) -> list[Book]:
        return [Book(id="1", title="Dune", author="Herbert")]


schema = strawberry.Schema(query=Query)

result = schema.execute_sync("{ books { id title author } }")
print(result.errors)
print(result.data)

Field Arguments और Defaults

GraphQL के arguments सीधे resolver parameters से आते हैं। Default value वाला parameter optional argument बन जाता है; default के बिना वाला required होता है।

  • Nullable, optional argument व्यक्त करने के लिए typing.Optional और default का उपयोग करें।
  • Strawberry incoming argument values को annotated Python type में अपने-आप coerce करती है।

नीचे, limit का default 10 है और genre एक optional filter है।

import strawberry
from typing import Optional


@strawberry.type
class Book:
    id: strawberry.ID
    title: str
    genre: str


LIBRARY = [
    Book(id="1", title="Dune", genre="scifi"),
    Book(id="2", title="It", genre="horror"),
]


@strawberry.type
class Query:
    @strawberry.field
    def books(self, limit: int = 10, genre: Optional[str] = None) -> list[Book]:
        items = LIBRARY if genre is None else [b for b in LIBRARY if b.genre == genre]
        return items[:limit]


schema = strawberry.Schema(query=Query)
print(schema.execute_sync('{ books(genre: "scifi") { title } }').data)

Mutations के लिए Input Types

Structured data स्वीकार करने वाली mutations में input type का उपयोग करना चाहिए: यह @strawberry.input से सजाई गई class होती है। Input types GraphQL में request body के समान हैं — वे mutation signatures को साफ़ और self-documenting रखते हैं।

  • जिन fields का default नहीं है, वे required input fields होते हैं।
  • जहाँ उचित हो, fields को optional बनाकर create/update flows में उसी input का पुनः उपयोग करें।
import strawberry
from typing import Optional


@strawberry.input
class AddBookInput:
    title: str
    author: str
    pages: Optional[int] = None

Mutation Root Type

Mutation root, Query के समान होता है, लेकिन writes व्यक्त करता है। प्रत्येक method एक @strawberry.mutation होती है। सामान्य तरीका यह है: input type लें, side effect करें और बनाया या अपडेट किया गया object लौटाएँ, ताकि client एक ही round trip में नए fields पढ़ सके।

यह उदाहरण in-memory store रखता है और नई Book लौटाता है। यह पूरी तरह standalone और चलाने योग्य है।

import strawberry

_DB: list["Book"] = []


@strawberry.type
class Book:
    id: strawberry.ID
    title: str
    author: str


@strawberry.input
class AddBookInput:
    title: str
    author: str


@strawberry.type
class Query:
    @strawberry.field
    def books(self) -> list[Book]:
        return _DB


@strawberry.type
class Mutation:
    @strawberry.mutation
    def add_book(self, data: AddBookInput) -> Book:
        book = Book(id=str(len(_DB) + 1), title=data.title, author=data.author)
        _DB.append(book)
        return book


schema = strawberry.Schema(query=Query, mutation=Mutation)
q = 'mutation { addBook(data: {title: "Dune", author: "Herbert"}) { id title } }'
print(schema.execute_sync(q).data)

Async Resolvers

क्योंकि Strawberry ASGI पर चलती है, resolvers async हो सकते हैं। FastAPI पर यह महत्वपूर्ण है: आपके resolvers event loop को block किए बिना database calls, HTTP clients या cache lookups के लिए await करेंगे।

  • बस async def घोषित करें — Strawberry इसे आपके लिए await करती है।
  • एक ही schema में sync और async resolvers को स्वतंत्र रूप से मिलाएँ।
  • किसी भी I/O के लिए async resolvers का उपयोग करें, ताकि कई fields वाली एक GraphQL request non-blocking बनी रहे।
import strawberry
import asyncio


@strawberry.type
class Stats:
    total_books: int


async def fetch_count() -> int:
    await asyncio.sleep(0)  # stand-in for an async DB call
    return 42


@strawberry.type
class Query:
    @strawberry.field
    async def stats(self) -> Stats:
        return Stats(total_books=await fetch_count())


schema = strawberry.Schema(query=Query)
print(asyncio.run(schema.execute("{ stats { totalBooks } }")).data)

GraphQLRouter के साथ FastAPI पर Mount करना

Strawberry strawberry.fastapi.GraphQLRouter देती है, जो एक APIRouter है और जिसे आप app.include_router के साथ mount करते हैं। यह उसी path पर GraphQL endpoint और browser के भीतर चलने वाली IDE (GraphiQL) उपलब्ध कराता है।

  • अपने बनाए हुए schema को router को दें।
  • इसे /graphql जैसे path के अंतर्गत mount करें।
  • Router FastAPI के event loop का उपयोग करता है, इसलिए async resolvers और FastAPI के startup/shutdown events साथ काम करते हैं।

यह framework code है, इसलिए bare judge पर नहीं चलाया जा सकता।

import strawberry
from fastapi import FastAPI
from strawberry.fastapi import GraphQLRouter


@strawberry.type
class Query:
    @strawberry.field
    def hello(self) -> str:
        return "world"


schema = strawberry.Schema(query=Query)
graphql_app = GraphQLRouter(schema)

app = FastAPI()
app.include_router(graphql_app, prefix="/graphql")

Context के माध्यम से Dependencies साझा करना

FastAPI पर mount करने का सबसे बड़ा लाभ shared dependencies हैं। GraphQLRouter को context_getter दें — यह FastAPI dependency callable है, इसलिए यह स्वयं DB session, current user या settings object पर Depends कर सकता है।

Context getter जो भी लौटाता है, वह resolvers के लिए strawberry.Info के माध्यम से info.context पर उपलब्ध होता है। इसी तरह authentication और database sessions FastAPI से आपके GraphQL resolvers तक पहुँचते हैं।

from fastapi import Depends
from strawberry.fastapi import GraphQLRouter


async def get_db():
    # yield a real async session in production
    yield {"connection": "db-session"}


async def get_context(db=Depends(get_db)):
    return {"db": db, "role": "reader"}


graphql_app = GraphQLRouter(schema, context_getter=get_context)

Resolvers के भीतर Context पढ़ना

Shared context का उपयोग करने के लिए resolver में info: strawberry.Info parameter जोड़ें। Strawberry इसे अपने-आप inject करती है और यह कभी GraphQL argument के रूप में दिखाई नहीं देता। अपनी dependencies को info.context के माध्यम से access करें।

  • info.context["db"] — context_getter द्वारा दिया गया session।
  • इसका उपयोग authorize करने के लिए करें: current user पढ़ें और permissions न होने पर error उठाएँ।
  • एक ही request के प्रत्येक resolver में वही context object साझा होता है।
import strawberry


@strawberry.type
class Query:
    @strawberry.field
    def current_role(self, info: strawberry.Info) -> str:
        return info.context["role"]

    @strawberry.field
    def secret(self, info: strawberry.Info) -> str:
        if info.context["role"] != "admin":
            raise Exception("forbidden")
        return "top-secret"

त्वरित जाँच: DB session साझा करना

आपने Strawberry schema को FastAPI पर mount किया है और चाहते हैं कि प्रत्येक GraphQL resolver उसी per-request database session का उपयोग करे, जो आपके REST endpoints को FastAPI dependency से मिलता है। इसे जोड़ने का idiomatic Strawberry + FastAPI तरीका क्या है?

पुनरावलोकन

आपने Strawberry के साथ एक typed GraphQL schema बनाया और उसे FastAPI पर mount किया:

  • Types: type-hinted fields वाली @strawberry.type classes; identifiers के लिए strawberry.ID और nullable fields के लिए Optional।
  • Query: read root, जिसमें @strawberry.field resolvers होते हैं और जिनके parameters GraphQL arguments बन जाते हैं।
  • Mutations: @strawberry.mutation methods, जो @strawberry.input type लेती हैं और प्रभावित object लौटाती हैं।
  • Schema: strawberry.Schema(query=Query, mutation=Mutation), जिसे execute_sync से verify किया जा सकता है।
  • FastAPI integration: GraphQLRouter के साथ mount करें और context_getter + info.context के माध्यम से DB sessions और auth साझा करें, तथा FastAPI के dependency injection का पुनः उपयोग करें।

यह code-first, type-safe तरीका आपके GraphQL API और FastAPI app को एक ही भाषा — Python type hints — में बात करने देता है।

शुरुआत निःशुल्क

एआई शिक्षक के साथ FastAPI बैकएंड डेवलपमेंट बूटकैंप सीखें — निःशुल्क

अपने ब्राउज़र में वास्तविक कोड लिखें और चलाएँ, चौबीसों घंटे एआई शिक्षक से तुरंत सहायता पाएँ, और वेब या ऐप पर वहीं से शुरू करें जहाँ आपने छोड़ा था।

पाठ्यक्रम
21
पाठ
84

अक्सर पूछे जाने वाले प्रश्न

क्या “प्रकार, क्वेरी और म्यूटेशन निर्धारित करना” पाठ निःशुल्क है?

हाँ — FastAPI बैकएंड डेवलपमेंट बूटकैंप अध्ययन पथ के 3 तक कोई भी पाठ, जिसमें “प्रकार, क्वेरी और म्यूटेशन निर्धारित करना” भी शामिल है, यहाँ वेब पर पूरा पढ़ना निःशुल्क है। इसके बाद CoddyKit PRO हर पाठ अनलॉक करता है, साथ ही अंतर्निर्मित कोड संपादक और चौबीसों घंटे एआई शिक्षक के साथ इंटरैक्टिव अभ्यास भी उपलब्ध कराता है। FastAPI बैकएंड डेवलपमेंट बूटकैंप पाठ्यक्रम में कुल 4 पाठ शामिल हैं।

“प्रकार, क्वेरी और म्यूटेशन निर्धारित करना” में मैं क्या सीखूँगा?

Strawberry के साथ टाइपयुक्त GraphQL स्कीमा बनाइए और साझा निर्भरताओं के साथ उसे FastAPI ऐप पर स्थापित कीजिए। आप ब्राउज़र में सीधे चलाए जाने वाले व्यावहारिक कोड के साथ FastAPI बैकएंड डेवलपमेंट बूटकैंप का अभ्यास करते हैं, और पाठ पूरा करते समय 24/7 एआई ट्यूटर आपके प्रश्नों के उत्तर देता है।

क्या FastAPI बैकएंड डेवलपमेंट बूटकैंप शुरू करने के लिए मुझे किसी अनुभव की आवश्यकता है?

पहले के अनुभव की आवश्यकता नहीं है। CoddyKit पर FastAPI बैकएंड डेवलपमेंट बूटकैंप शुरुआती से लेकर उन्नत शिक्षार्थियों तक सभी के लिए व्यवस्थित किया गया है, इसलिए आप यहीं से या शुरुआत से सीखना शुरू कर सकते हैं और अपनी गति से आगे बढ़ सकते हैं। यह 4 में से 1वाँ पाठ है।

“प्रकार, क्वेरी और म्यूटेशन निर्धारित करना” पाठ पूरा करने में कितना समय लगता है?

CoddyKit का अधिकांश पाठ लगभग 5–10 मिनट में पूरा हो जाता है। हर पाठ छोटा और संवादात्मक है, इसलिए आप लगातार प्रगति करते हैं और वेब या ऐप पर वहीं से सीखना जारी रख सकते हैं जहाँ आपने छोड़ा था।

क्या मैं इस FastAPI बैकएंड डेवलपमेंट बूटकैंप पाठ में कोड लिख और चला सकता हूँ?

हाँ। हर FastAPI बैकएंड डेवलपमेंट बूटकैंप पाठ में एक अंतर्निर्मित कोड संपादक शामिल है, जिससे आप सीधे अपने ब्राउज़र में वास्तविक कोड लिख और चला सकते हैं और तुरंत एआई प्रतिक्रिया पा सकते हैं—स्थानीय सेटअप की आवश्यकता नहीं है।

इस पाठ्यक्रम के सभी पाठ

  1. प्रकार, क्वेरी और म्यूटेशन निर्धारित करना
  2. DataLoaders से N+1 क्वेरी हल करना
  3. रीयल-टाइम GraphQL सब्सक्रिप्शन
  4. क्वेरी लागत विश्लेषण और गहराई सीमा
← FastAPI बैकएंड डेवलपमेंट बूटकैंप पर वापस जाएँ