Friday, 4 February 2022

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

FastAPI: status_code: Specify response status code

By setting 'status_code' parameter to the decorator method (@app.get(), @app.post(), @app.put(), @app.delete()), we can explicilty set the return code.

 

Example

@app.post("/emps", status_code=201)
def createEmployee(emp: Employee):
    noOfEmps = len(emps)
    newId = noOfEmps + 1
    emps[newId] = emp
    return {"id" : newId, "name" : emp.name, "age": emp.age, "country": emp.country}

 

Find the below working application.

 

statusCode.py

from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
from enum import Enum

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.post("/emps", status_code=201)
def createEmployee(emp: Employee):
    noOfEmps = len(emps)
    newId = noOfEmps + 1
    emps[newId] = emp
    return {"id" : newId, "name" : emp.name, "age": emp.age, "country": emp.country}

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

 

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

 

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

 


 

  

Previous                                                    Next                                                    Home

JanusGraph: Get all the outgoing edges of vertex

By supplying Direction.OUT argument to the edges method, we can get all the outgoing edges of a vertex.

 

public Iterator<Edge> edges(final Direction direction, final String... edgeLabels);

Gets an Iterator of incident edges. Argument 'direction' specifies the incident direction of the edges to retrieve off this vertex. Direction can be IN, OUT, BOTH. Argument 'edgeLabels' specifies the labels of the edges to retrieve. If no labels are provided, then get all edges.

 

Example

Iterator<Edge> edges = ramVertex.edges(Direction.OUT);
while (edges.hasNext()) {
	Edge edge = edges.next();
	System.out.println(edge.outVertex().property("name").value() + "--" + edge.label() + "-->" + edge.inVertex().property("name").value());
}

 

Find the below working application.

 

OutgoingEdges.java
package com.sample.app.edges;

import java.util.Iterator;

import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.JanusGraphVertex;

public class OutgoingEdges {
	public static void main(String args[]) {

		JanusGraph janusGraph = null;

		try {
			janusGraph = JanusGraphFactory.open("/Users/Shared/janus.properties");

			// Create a person vertex
			JanusGraphVertex krishnaVertex = janusGraph.addVertex("person");
			krishnaVertex.property("name", "Krishna");
			krishnaVertex.property("age", 31);
			krishnaVertex.property("gender", 'M');

			// Create a person vertex
			JanusGraphVertex ramVertex = janusGraph.addVertex("person");
			ramVertex.property("name", "Ram");
			ramVertex.property("age", 34);
			ramVertex.property("gender", 'M');

			// Create a person vertex
			JanusGraphVertex rahimVertex = janusGraph.addVertex("person");
			rahimVertex.property("name", "Rahim");
			rahimVertex.property("age", 41);
			rahimVertex.property("gender", 'M');

			ramVertex.addEdge("knows", krishnaVertex, "from", 2017, "colleague", "N");
			rahimVertex.addEdge("knows", ramVertex, "from", 2019, "colleague", "Y");

			janusGraph.tx().commit();

			Iterator<Edge> edges = ramVertex.edges(Direction.OUT);
			while (edges.hasNext()) {
				Edge edge = edges.next();
				System.out.println(edge.outVertex().property("name").value() + "--" + edge.label() + "-->"
						+ edge.inVertex().property("name").value());
			}

		} finally {
			janusGraph.close();
			System.out.println("Done!!!");
		}

	}
}

Output

Ram--knows-->Krishna
Done!!!

 

  

Previous                                                 Next                                                 Home