Nov-09-2022, 11:42 PM
Hello, I am writing a POST API.
My intention is to retrieve an IP address and save into a database.
When I go to Postman and I hit the API endpoint, I am getting the following from Postman:
http://127.0.0.1:8000/ip
In the Body I put:
Key=IP value=1.1.1.1
Postman answer:
{
"detail": [
{
"loc": [
"body"
],
"msg": "value is not a valid dict",
"type": "type_error.dict"
}
]
}
Code:
My intention is to retrieve an IP address and save into a database.
When I go to Postman and I hit the API endpoint, I am getting the following from Postman:
http://127.0.0.1:8000/ip
In the Body I put:
Key=IP value=1.1.1.1
Postman answer:
{
"detail": [
{
"loc": [
"body"
],
"msg": "value is not a valid dict",
"type": "type_error.dict"
}
]
}
Code:
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
IP: str
app = FastAPI()
@app.post("/ip")
async def create_item(item: Item):
database = "apix.db"
table = "APIW"
savetodb(database, table, item)
return {'ip':item}
def savetodb(database, table, ip):
connection_obj = sqlite3.connect(database)
cursor_obj = connection_obj.cursor()
cursor_obj.execute("DROP TABLE IF EXISTS " + table)
table = """ CREATE TABLE """ + table + """ (
VARCHAR(255) NOT NULL
); """
cursor_obj.execute(table)
#For now hardcoding this
connection_obj.execute ("""INSERT INTO APIW (IP) VALUES ("1.1.1.1")""")
#connection_obj.execute ("""INSERT INTO """ +table+ """(IP) VALUES (""" + ip + ")""")
connection_obj.commit()
connection_obj.close()
