The rest of the python code doesn't work with FastAPI

Question:

I want to make a discord bot that would work with data that would be sent from a web application via POST request. So for that I need to make my own API containing that POST request with FastAPI.

My question is: how can make my API work with the rest of the code?

Consider this example:

from fastapi import FastAPI, Request
from pydantic import BaseModel

app = FastAPI()

dict = {"name": "","description": ""}

class Item(BaseModel):
    name: str
    description: str

@app.post("/item")
async def create_item(request: Request, item: Item):
    result = await request.json()
    dict["name"] = result["name"]
    print(dict)

print(dict)

When I run the API, type the values in and print dict for the fist time, it outputs something like that: {'name': 'some_name', 'desc': 'some_desc'}
But when I run my file as python code, only {'name': '', 'desc': ''} gets printed out.

I thought that after I type in values in dict on my API page (https://localhost:800/docs), python would output the exact values I typed, but it didn’t happen.

What do I do?

Asked By: syrok

||

Answers:

You did not return the dict data to client.

This code will works

from fastapi import FastAPI, Request
from pydantic import BaseModel

app = FastAPI()

dict = {"name": "","description": ""}

class Item(BaseModel):
    name: str
    description: str

@app.post("/item")
async def create_item(request: Request, item: Item):
    result = await request.json()
    dict["name"] = result["name"]
    dict["description"] = result["description"]
    print(dict)
    return dict

Test by Postman.
enter image description here

In terminal at VS code,
enter image description here

Answered By: Bench Vue

When you call the api, you essentially call the create_item function, which would manipulate your dictionary. When you directly run your python code, you don’t call the create_item function, therefore the dictionary isn’t manipulated, and you get the original dictionary back, which is {'name': '', 'desc': ''}.

When you run your server, it runs in it’s own instance. When you run your file again with python, it’s another instance. They’re two seperate things that don’t know each other’s "dict" values.

If you want to know about when your api manipulates something (if you want your data to persist regardless of your python instances), you should use a database and query said database (you can even use a .json file for that purpose)

Answered By: sergenp
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.