विषय पर बढ़ें

Tutorial - Input parameters को handle करना

Query string से parameters pass करना

आइए operation को बदलें ताकि वह URL query string से एक name accept कर सके। ऐसा करने के लिए, बस अपने function में एक name argument जोड़ें।

@api.get("/hello")
def hello(request, name):
    return f"Hello {name}"

जब हम named argument provide करते हैं, तो हमें अपेक्षित (HTTP 200) response मिलता है।

localhost:8000/api/hello?name=you:

"Hello you"

Default values

अगर आप parameter provide नहीं करते, तो एक HTTP 422 error response return होता है।

localhost:8000/api/hello:

{
  "detail": [
    {
      "loc": ["query", "name"],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}

हम name argument के लिए एक default value specify कर सकते हैं, ताकि अगर वह न दिया गया हो तो भी काम चले:

@api.get("/hello")
def hello(request, name="world"):
    return f"Hello {name}"

Input types

Django Ninja input types को format करने के लिए standard Python type hints का इस्तेमाल करता है। अगर कोई type नहीं दिया गया है, तो string मान लिया जाता है (लेकिन सभी arguments के लिए type hints देना best practice है)।

आइए एक दूसरा operation जोड़ें जो integers के साथ कुछ बुनियादी math करता है।

@api.get("/hello")
def hello(request, name: str = "world"):
    return f"Hello {name}"

@api.get("/math")
def math(request, a: int, b: int):
    return {"add": a + b, "multiply": a * b}

localhost:8000/api/math?a=2&b=3:

{
  "add": 5,
  "multiply": 6
}

Path strings के ज़रिए parameters pass करना

आप Python format strings के समान syntax का इस्तेमाल करके path "parameters" declare कर सकते हैं।

Path string में मिला कोई भी parameter query string से लिए जाने की बजाय आपके function को एक argument के रूप में pass किया जाएगा।

@api.get("/math/{a}and{b}")
def math(request, a: int, b: int):
    return {"add": a + b, "multiply": a * b}

अब हम localhost:8000/api/math/2and3 के ज़रिए math operation को access करते हैं।

Request body के ज़रिए parameters pass करना

हम hello operation को बदलकर एक HTTP POST request का इस्तेमाल करने वाला बनाएँगे, और parameters को request body से लेंगे।

यह specify करने के लिए कि parameters request body से आते हैं, हमें एक schema declare करना होगा।

from ninja import NinjaAPI, Schema

api = NinjaAPI()

class HelloSchema(Schema):
    name: str = "world"

@api.post("/hello")
def hello(request, data: HelloSchema):
    return f"Hello {data.name}"

Self-documenting API

अब localhost:8000/api/hello पर जाने पर एक HTTP 405 error response मिलेगा, क्योंकि हमें इस URL पर किए जाने वाले request को POST type में बदलना है।

ऐसा करने का एक आसान तरीका है Swagger documentation का इस्तेमाल करना जो हमारे लिए automatically बन जाती है, default "/docs" URL पर (हमारे API URL root के आगे जुड़ा हुआ)।

  1. localhost:8000/api/docs पर जाएँ और उन operations को देखें जो हमने बनाए
  2. /api/hello operation खोलें
  3. "Try it out" पर click करें
  4. Request body को modify करें
  5. "Execute" पर click करें

Success

अगले chapter Responses को handle करना पर बढ़ें।

टिप्पणियाँ


पेज व्यूज़: