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

JanusGraph: get all the edge property keys

keys() method return the keys of the properties associated with this element.

 

Example

Set<String> propertyKeys = janusGraphEdge.keys();
for (String key : propertyKeys) {
	System.out.println(key + " --> " + janusGraphEdge.property(key).value());
}

 

GetAllEdgeProperties.java

package com.sample.app.edges;

import java.util.Set;

import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphEdge;
import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.JanusGraphVertex;

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

		try (JanusGraph 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');

			JanusGraphEdge janusGraphEdge = ramVertex.addEdge("knows", krishnaVertex, "colleague", "N");
			janusGraphEdge.property("since", 2017);

			janusGraph.tx().commit();

			System.out.println("Edge properties:");
			Set<String> propertyKeys = janusGraphEdge.keys();
			for (String key : propertyKeys) {
				System.out.println("\t" + key + " --> " + janusGraphEdge.property(key).value());
			}

		} finally {

			System.out.println("\nDone!!!");
		}

	}
}

 

Output

Edge properties:
	colleague --> N
	since --> 2017

Done!!!

 

 

 

 

 

Previous                                                 Next                                                 Home

JanusGraph: Attach properties to an edge

There are two ways to attach property to an edge.

 

At the time of edge creation

JanusGraphEdge janusGraphEdge = ramVertex.addEdge("knows", krishnaVertex, "colleague", "N");

Above snippet attach the property ‘colleague’ and assign the value N to it.

 

Using property method

Using 'property' method, you can attach properties to a janus edge.

 

Example

janusGraphEdge.property("since", 2017);

Find the below working example.

 

AttachPropertiesToEdge.java

package com.sample.app.edges;

import java.util.Set;

import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphEdge;
import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.JanusGraphVertex;

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

		try (JanusGraph 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');

			JanusGraphEdge janusGraphEdge = ramVertex.addEdge("knows", krishnaVertex, "colleague", "N");
			janusGraphEdge.property("since", 2017);

			janusGraph.tx().commit();

			Set<String> propertyKeys = janusGraphEdge.keys();
			for (String key : propertyKeys) {
				System.out.println(key + " --> " + janusGraphEdge.property(key).value());
			}

		} finally {

			System.out.println("Done!!!");
		}

	}
}

Output

colleague --> N
since --> 2017
Done!!!



 

Previous                                                 Next                                                 Home

JasunGraph: Get edge label

label() method return the edge label name.

 

Example

JanusGraphEdge janusGraphEdge = ramVertex.addEdge("knows", krishnaVertex, "from", 2017, "colleague", "N");
String labelName = janusGraphEdge.label();

 

Find the below working application.

 

EdgeLabel.java

package com.sample.app.edges;

import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphEdge;
import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.JanusGraphVertex;

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

		try (JanusGraph 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');

			JanusGraphEdge janusGraphEdge = ramVertex.addEdge("knows", krishnaVertex, "from", 2017, "colleague", "N");

			janusGraph.tx().commit();

			String labelName = janusGraphEdge.label();
			System.out.println("labelName : " + labelName);
		} finally {

			System.out.println("Done!!!");
		}

	}
}

Output

labelName : knows
Done!!!


 

Previous                                                 Next                                                 Home

JanusGraph: Get the id of edge

id() method return the unique identifier of the edge.

 

Example

JanusGraphEdge janusGraphEdge = ramVertex.addEdge("knows", krishnaVertex, "from", 2017, "colleague", "N");
Object id = janusGraphEdge.id();

 

Find the below working application.

 

GetEdgeId.java

package com.sample.app.edges;

import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphEdge;
import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.JanusGraphVertex;

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

		try (JanusGraph 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');

			JanusGraphEdge janusGraphEdge = ramVertex.addEdge("knows", krishnaVertex, "from", 2017, "colleague", "N");

			janusGraph.tx().commit();

			Object id = janusGraphEdge.id();
			System.out.println("id : " + id);
		} finally {

			System.out.println("Done!!!");
		}

	}
}

 

Output

id : 1crw8x-1crx1k-azv9-oe08g
Done!!!

 

 

 

 

 

Previous                                                 Next                                                 Home

Exploring JanusGraphEdge

 


            JanusGraph: Get the id of edge
            JasunGraph: Get edge label
            JanusGraph: Attach properties to an edge
            JanusGraph: get all the edge property keys
            JanusGraph: Get all the vertices associated with the edge
            JanusGraph: Get outgoing vertex of this edge
            JanusGraph: get incoming vertex of the edge
            JanusGraph: Get outgoing and incoming vertices of the edge

Previous                                                 Next                                                 Home