Showing posts with label fastapi. Show all posts
Showing posts with label fastapi. Show all posts

Sunday, 6 February 2022

Can I pass a dictionary, list or any object while raising HttpException?

Yes, you can pass any value that can be converted to JSON as the parameter ‘detail’.

 

Example

@app.get("/emps/by-id/{empId}")
def empById(empId: int = Path(None, description = "Enter valid employee id")):
    if(empId not in emps):
        raise HTTPException(
                status_code=404, 
                detail={"msg" : "Employee not found", "id" : empId}
            )
            
    return emps[empId]   

 

Find the below working application.

 

throwHttpException2.py
from fastapi import FastAPI, Path, HTTPException
from pydantic import BaseModel

app = FastAPI()

# model classes
class Employee(BaseModel):
    name: str
    age: int
    country: str

# employees information
emps = {
    1 : {
        "name" : "Krishna",
        "age": 32,
        "country": "India"
    },
    2 : {
        "name" : "Ram",
        "age": 33,
        "country": "China"
    },
    3 : {
        "name" : "Bomma",
        "age": 38,
        "country": "China"
    }
}

# Create home endpoint
@app.get("/")
def home():
    return {"name" : "Hello World app", "version": "2.0.0"}

# Employees REST APIs
@app.get("/emps")
def allEmployees():
    return emps
    
@app.get("/emps/by-id/{empId}")
def empById(empId: int = Path(None, description = "Enter valid employee id")):
    if(empId not in emps):
        raise HTTPException(
                status_code=404, 
                detail={"msg" : "Employee not found", "id" : empId}
            )
            
    return emps[empId]    

 

Open terminal and execute the command ‘uvicorn throwHttpException2:app --reload’.

$uvicorn throwHttpException2:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [63568] using statreload
INFO:     Started server process [63570]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

  Open the url ‘http://localhost:8000/docs’ in browser and execute the api 'GET ​/emps​/by-id​/{empId}' for empId 4, you will get http status code 404 and custom error object in the response body.

 


 

 

  

Previous                                                    Next                                                    Home

Friday, 4 February 2022

FastAPI: HTTPException: Return response with errors

Using ‘HTTPException’, you can return HTTP responses with errors to the client.

 

Example

@app.get("/emps/by-id/{empId}")
def empById(empId: int = Path(None, description = "Enter valid employee id")):
    if(empId not in emps):
        raise HTTPException(status_code=404, detail="Item not found")
    return emps[empId]    

 

throwHttpException.py

from fastapi import FastAPI, Path, HTTPException
from pydantic import BaseModel

app = FastAPI()

# model classes
class Employee(BaseModel):
    name: str
    age: int
    country: str

# employees information
emps = {
    1 : {
        "name" : "Krishna",
        "age": 32,
        "country": "India"
    },
    2 : {
        "name" : "Ram",
        "age": 33,
        "country": "China"
    },
    3 : {
        "name" : "Bomma",
        "age": 38,
        "country": "China"
    }
}

# Create home endpoint
@app.get("/")
def home():
    return {"name" : "Hello World app", "version": "2.0.0"}

# Employees REST APIs
@app.get("/emps")
def allEmployees():
    return emps
    
@app.get("/emps/by-id/{empId}")
def empById(empId: int = Path(None, description = "Enter valid employee id")):
    if(empId not in emps):
        raise HTTPException(status_code=404, detail="Employee not found")
    return emps[empId]    

 

Open terminal and execute the command ‘uvicorn throwHttpException:app --reload’.

 

$uvicorn throwHttpException:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [25209] using statreload
INFO:     Started server process [25211]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

  Open the url ‘http://localhost:8000/docs’ in browser and execute the api 'GET ​/emps​/by-id​/{empId}' for empId 4, you will get http status code 404.

 


 

 

 

Previous                                                    Next                                                    Home

FastAPI: Upload file and additional form parameters

In this post, I am going to explain how to upload a file along with additional form parameters. By defining the files and form fields at the same time using File and Form we can upload the file and additional form parameters.

 

Example

@app.post("/upload")
def uploadData(files:List[UploadFile] = File(...), msg : str = Form(...))

Find the below working application.

 

fileAndFormParam.py

from fastapi import FastAPI, File, UploadFile, Form
from typing import List

app = FastAPI()

@app.post("/upload")
def uploadData(files:List[UploadFile] = File(...),
                             msg : str = Form(...)):
    fileNames = []

    for file in files:
        fileNames.append(file.filename)

    return {"fileNames": fileNames, 'msg' : msg}

Open terminal and execute the command ‘uvicorn fileAndFormParam:app --reload’.

$uvicorn fileAndFormParam:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [65890] using statreload
INFO:     Started server process [65892]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Open the url ‘http://localhost:8000/docs’ in browser and experiment with the swagger documentation.





  

Previous                                                    Next                                                    Home

Wednesday, 2 February 2022

FastAPI: Multiple file uploads example

FastAPI allows you to upload multiple files in at the same time.

 

Example 1: Using List[bytes]

@app.post("/files/")
async def create_file(files: List[bytes] = File(...)):
    contentReceived = []

    for file in files:
        contentReceived.append(str(file))

    return {"contentReceived": contentReceived}

 

Example 2: Using List[UploadFile]

@app.post("/uploadfiles/")
async def create_upload_file(files:List[UploadFile] = File(...)):
    fileNames = []

    for file in files:
        fileNames.append(file.filename)

    return {"fileNames": fileNames}

Find the below working application.

 

multipleFileuploads.py

from fastapi import FastAPI, File, UploadFile
from typing import List

app = FastAPI()

@app.post("/files/")
async def create_file(files: List[bytes] = File(...)):
    contentReceived = []

    for file in files:
        contentReceived.append(str(file))

    return {"contentReceived": contentReceived}

@app.post("/uploadfiles/")
async def create_upload_file(files:List[UploadFile] = File(...)):
    fileNames = []

    for file in files:
        fileNames.append(file.filename)

    return {"fileNames": fileNames}

Open terminal and execute the command ‘uvicorn multipleFileuploads:app --reload’.

$uvicorn multipleFileuploads:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [28879] using statreload
INFO:     Started server process [28881]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

 Open the url ‘http://localhost:8000/docs’ in browser and experiment with swagger documentation.


 
 

Previous                                                    Next                                                    Home

FastAPI: Upload a file

We can upload the file using File function.

Prerequisite

Install ‘python-multipart’ module.

 

pip install python-multipart

pip3 install python-multipart

 

Step 1: Import File, UploadFile from fastapi module.

from fastapi import FastAPI, File, UploadFile

 

Step 2: Define File parameters.

 

Reading as bytes

@app.post("/files/")
async def create_file(file: bytes = File(...)):
    return {"file_size": len(file), "data_received" : str(file)}

 File content is read as bytes and content is uploaded as form data. In this example, file content will be read into in-memory. Use this option while reading small size files.

 

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    content = file.file.read()
    return {"filename": file.filename, "data_received": content}

 

'UploadFile' store the file content in memory upto certain size and after passing this limit it stores the file to disk.

 

uploadFile1.py

 

from fastapi import FastAPI, File, UploadFile

app = FastAPI()

@app.post("/files/")
async def create_file(file: bytes = File(...)):
    return {"file_size": len(file), "data_received" : str(file)}

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    content = file.file.read()
    return {"filename": file.filename, "data_received": content}

Open terminal and execute the command ‘uvicorn uploadFile1:app --reload’.

$ uvicorn uploadFile1:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [44194] using statreload
INFO:     Started server process [44196]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Open the url ‘http://localhost:8000/docs’ in browser and experiment with the apis.


 

Previous                                                    Next                                                    Home

FastAPI: define request to receive form data (x-www-form-urlencoded)

Using Form function, we can specify the form fields.

 

formRequest.py

from fastapi import FastAPI, Form

app = FastAPI()

@app.post("/register-me", status_code=201)
async def login(
    username: str = Form(...), 
    password: str = Form(...),
    country: str = Form(...)):
    return {"username": username, "country": country}

 Open terminal and execute the command ‘uvicorn formRequest:app --reload’.

$uvicorn formRequest:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [83472] using statreload
INFO:     Started server process [83474]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Open the url ‘http://localhost:8000/docs’ in browser and experiment with the api /register-me.

 

  

Previous                                                    Next                                                    Home