question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

FastAPI JSON weird

See original GitHub issue

So, I’m not sure which library bears responsibility here, but I’ll start with ormar and you can forward me somewhere else if the problem lies elsewhere. Consider the following code:

...
class Thing(ormar.Model):
    class Meta(BaseMeta):
        tablename = "things"
    id: UUID = ormar.UUID(primary_key=True, default=uuid4)
    name: str = ormar.Text(default="")
    js: pydantic.Json = ormar.JSON()
...
@app.get("/things")
async def read_things():
    return await Thing.objects.all()
...

What I get when I call this endpoint is e.g.

[
  {
    "id": "1932caad-1157-4224-9688-e280f9623e67",
    "name": "",
    "js": "[\"asdf\", \"asdf\", \"bobby\", \"nigel\"]"
  },
  {
    "id": "3e6a15b2-2cd5-456b-a4dc-24e3cd76d96e",
    "name": "test",
    "js": "[\"lemon\", \"raspberry\", \"lime\", \"pumice\"]"
  }
]

Note how rather than being JSON, the js field is a plain string containing JSON. Is this on purpose? Does it HAVE to be that way? It seems to me like it would make more sense for a JSON field, when its container is serialized to JSON, to just…be JSON. (I note that thing.json() preserves the “convert json to string” behavior.) Is there an easy way around this behavior, perhaps a flag or setting? Is this actually a result of a different library?

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:13 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
Erhanniscommented, Feb 15, 2021

Great, that works. Thanks! I’ll open more tickets if I find anything else weird or wrong.

On Mon, Feb 15, 2021, 2:10 PM collerek notifications@github.com wrote:

Yeah, it was changed in one of the old version to be in line with pydantic where you have to specifically set field to optional or provide a default value for the field to be not required. See that i forgot to update the nullable part of docs, thanks for the tip, will change that.

As for the rules below is the section from the docs overview:

All fields are required unless one of the following is set:

  • nullable - Creates a nullable column. Sets the default to None.
  • default - Set a default value for the field.
  • server_default - Set a default value for the field on server side (like sqlalchemy’s func.now()).
  • primary key with autoincrement - When a column is set to primary key and autoincrement is set on this column. Autoincrement is set by default on int primary keys.
  • pydantic_only - Field is available only as normal pydantic field, not stored in the database.

So in your case you should just set nullable=True on js Field.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/collerek/ormar/issues/95#issuecomment-779404720, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAXCNTPSMFO2HFNLPX4OI4DS7FWTHANCNFSM4XMBS25Q .

0reactions
collerekcommented, Feb 15, 2021

Yeah, it was changed in one of the old version to be in line with pydantic where you have to specifically set field to optional or provide a default value for the field to be not required. See that i forgot to update the nullable part of docs, thanks for the tip, will change that.

As for the rules below is the section from the docs overview:

All fields are required unless one of the following is set:

  • nullable - Creates a nullable column. Sets the default to None.
  • default - Set a default value for the field.
  • server_default - Set a default value for the field on server side (like sqlalchemy’s func.now()).
  • primary key with autoincrement - When a column is set to primary key and autoincrement is set on this column. Autoincrement is set by default on int primary keys.
  • pydantic_only - Field is available only as normal pydantic field, not stored in the database.

Also relation fields by default are nullable.

So in your case you should just set nullable=True on js Field.

Read more comments on GitHub >

github_iconTop Results From Across the Web

tiangolo/fastapi - Gitter
So in my api I'm returning a pydantic model, and fastAPI is converting it to json. If I test or demonstrate a endpoint...
Read more >
Fast API : How to return a str as JSON - python - Stack Overflow
I investigated as it was strange that the Fast API example didn't work. The problem was that I was not using the right...
Read more >
Many-To-Many Relationships In FastAPI - GormAnalysis
In this tutorial, I cover multiple strategies for handling many-to-many relationships using FastAPI with SQLAlchemy and pydantic.
Read more >
Multiple Models with FastAPI - SQLModel - tiangolo
Here's the weird thing, the id currently seems also "optional". ... Now we use the type annotation HeroCreate for the request JSON data...
Read more >
FastAPI Best Practices : r/Python - Reddit
construct() as a dict and not the model. But most often, the data is being read to be immediately encoded and return to...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found