3

i have a ressource and want to have a post api endpoint to modify it. My problem is if i set all propertys Optional[...] how did i know if i want to "delete" one property or set it to null? If i set it in the request to null: I get NoneType. But if i don't set it in the request i also get NoneType. Is there a solution to differ between this cases?

Here is an example program:

from typing import Optional
from fastapi import FastAPI
import uvicorn
from pydantic import BaseModel


class TestEntity(BaseModel):
    first: Optional[str]
    second: Optional[str]
    third: Optional[str]


app = FastAPI()


@app.post("/test")
    def test(entity: TestEntity):
    return entity


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=5000)

I want to set first to null and don't do anything with the other propertys, I do:

{
  "first":null
}

via POST request. As response I get:

{
  "first": null,
  "second": null,
  "third": null
}

As you can see you cannot know which property is set null and which propertys should remain the same.

5
  • For most practical intents and purposes: null means "no value", so where's the difference between the value not existing and the entire property not existing?
    – deceze
    Oct 20, 2021 at 11:57
  • In another program i want to set something to null. But i cannot differ if it is given in the request or not
    – Nico
    Oct 20, 2021 at 11:59
  • 1
    @Nico If fields are optional, they would be set to NULL by default in DB, None in python and null in json. Since you are creating a resource with only one property, you are essentially setting other properties to null indirectly. Had it been the case of PATCH, and if you send null for first, then only that field will get updated.
    – gsb22
    Oct 20, 2021 at 12:08
  • 2
    Have you seen stackoverflow.com/questions/66229384/… ? This shows how you can see whether a field was included in the request schema or not; so for updates you can deal exclusively with those fields that had a value provided.
    – MatsLindh
    Oct 20, 2021 at 12:27
  • 1
    @deceze There is a semantic difference between "the value was not provided, because the update should only concern specific fields" (i.e. it should be left as it is) and "the value was explicitly set to null". This is in the context of modifying an existing document, not creating it.
    – MatsLindh
    Oct 20, 2021 at 12:28

1 Answer 1

0

You can find your answer here : Pydantic: Detect if a field value is missing or given as null

@app.post("/test")
def test(entity: TestEntity):
    return entity.dict(exclude_unset=True)

Not the answer you're looking for? Browse other questions tagged or ask your own question.