GET Method Using FastAPI- JSON Server

# Get all details of user

@app.get("/user/list/")

def display_user_detail():

with open("test.json", 'r') as file:

dict = json.load(file)

return dict

# Get detail by user_id

@app.get("/user/{user_id}/")

def display_user(user_id: str):

with open("test.json", 'r') as file:

dict = json.load(file)

return dict[user_id]

View More...

Delete Method Using FastAPI- JSON Server

@app.delete("/user/{user_id}/", status_code=202)

def display_user(user_id: str):

response = {"status": True, "message": "Data has been deleted!", "data":[]}

try:

with open("test.json", 'r') as file:

dict = json.load(file)

except Exception as e:

#print(str(e))

dict = {}

if user_id in dict:

del dict[user_id]

if os.stat('test.json').st_size > 0:

data = json.dumps(dict, indent=4)

with open("test.json", 'w') as file:

file.write(data)

response["data"] = data

else:

response["message"] = "data does not exits!"

response["status"] = False

return response

View More...

Create Registration (POST Method ) using FastAPI- JSON Server

from typing import Optional

from fastapi import FastAPI

import json

import os

import os.path

from enum import Enum

from pydantic import BaseModel

app = FastAPI()

class Status(str, Enum):

ACTIVE = 'ACTIVE'

RECEIVED = 'RECEIVED'

class UserCreate(BaseModel):

first_name: str

last_name: Optional[str] = None

age: int

skill: list

dept: str

status: Status = Status.ACTIVE

# POST method

@app.post("/user/create")

def create(User: UserCreate):

file_exists = os.path.exists('test.json')

if file_exists:

try:

with open("test.json", 'r') as file:

dict = json.load(file)

except:

dict = {}

dict1 = {

f"user{len(dict)}": {

"name": User.first_name,

"last_name": User.last_name,

"age" : User.age,

"skill" : User.skill,

"dept" : User.dept,

"status" : User.status,

}

}

dict.update(dict1)

final_file = json.dumps(dict, indent=4)

with open("test.json", 'w') as file:

file.write(final_file)

else:

f = open("test.json", 'x')

print("file created!!!!")

return dict

View More...

FastAPI --Image File upload

from fastapi import FastAPI, UploadFile, File

app = FastAPI()

# Image Uploading

@app.post("/uploadimage")

def upload_image(imagefile: UploadFile = File(...)):

image_location = f"images/{imagefile.filename}"

with open(image_location, "wb+") as image:

shutil.copyfileobj(imagefile.file, image)

return {"msg": f" image '{imagefile.filename}' saved in '{image_location}' "}

View More...

dump() vs dumps() && load() vs loads()

 json.dumps(): json.dumps() method can convert a Python object into a JSON string.

Syntax: json.dumps(dict, indent)

json.dump(): json.dump() method can be used for writing to JSON file.

Syntax: json.dump(dict, file_pointet)

json.load () vs json.loads()

Json.load(): takes a file object and returns the json object. It is used to read JSON encoded data from a

file and convert it into a Python dictionary and deserialize a file itself i.e. it accepts a file object.

Syntax: json.load(fp, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

Json.loads(): method can be used to parse a valid JSON string and convert it into a Python Dictionary. It is mainly used for deserializing native string, byte, or byte array which consists of JSON data into Python Dictionary.

Syntax: json.loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

View More...

First Previous 3 4 5 6 7 Next Last