Sunday, 30 January 2022

FastAPI: response_model_exclude_unset: exclude unset values

By setting the decorator parameter response_model_exclude_unset=True, we can exclude unset values in the response model.

 

Example

@app.get("/emps/by-id/{empId}", response_model = Employee, response_model_exclude_unset=True)
def empById(empId: int = Path(None, description = "Enter valid employee id", gt = 0, lt = 4))

 

Find the below working application.

 

responseModelExcludeUnset.py

 

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

app = FastAPI()

class CountryEnum(str, Enum):
    India = "India"
    China = "China"
    Russia = "Russia"

# model classes
class Employee(BaseModel):
    name: str
    age: int
    country: str = 'India'
    tax: float = 30.5

emp1 = Employee(name= "Krishna", age = 32, country = "India", tax = 20)
emp2 = Employee(name= "Ram", age = 42, country = "China", tax = 35)
emp3 = Employee(name= "Sailu", age = 33)

employees = {1 : emp1, 2 : emp2, 3 : emp3}

@app.get("/emps/by-id/{empId}", response_model = Employee, response_model_exclude_unset=True)
def empById(empId: int = Path(None, description = "Enter valid employee id", gt = 0, lt = 4)):
    if(empId in employees):
        return employees[empId]
    else:
        raise Exception("Employee not exist with given id " + str(empId))

Open terminal and execute the command 'uvicorn responseModelExcludeUnset:app --reload'.

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

Open the url ‘http://localhost:8000/docs’ in browser and experiment with the api ‘GET /emps​/by-id​/{empId}’



As you see above snippet, ‘country’ and ‘tax’ are excluded and only ‘name’ and ‘age’ fields are returned for employee id 3.


  

Previous                                                    Next                                                    Home

JanusGraph: Get the vertex by id

Below snippet get the vertex by id.

Iterator<Vertex> janusGraphVertexes = janusGraph.vertices(janusGraphVertex.id());
Vertex vertex = janusGraphVertexes.next();

 

Find the below working application.

 

AddVertex.java
package com.sample.app.vertex;

import java.util.Iterator;
import java.util.Set;

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

public class AddVertex {

	public static void main(String args[]) {

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

		// Create a person vertex
		JanusGraphVertex janusGraphVertex = janusGraph.addVertex("person");

		// Add properties to the vertex
		janusGraphVertex.property("name", "Krishna");
		janusGraphVertex.property("age", 31);
		janusGraphVertex.property("gender", 'M');

		janusGraph.tx().commit();

		Iterator<Vertex> janusGraphVertexes = janusGraph.vertices(janusGraphVertex.id());
		Vertex vertex = janusGraphVertexes.next();

		System.out.println("-----------------------------");
		System.out.println("id : " + vertex.id());
		System.out.println("long id : " + ((JanusGraphVertex) vertex).longId());
		System.out.println("label : " + vertex.label());

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

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

}

 

Output

-----------------------------
id : 4184
long id : 4184
label : person
properties
	gender -> M
	name -> Krishna
	age -> 31
-----------------------------
Done!!!

 

 

 

 

Previous                                                 Next                                                 Home

JanusGraph: Create a vertex

Step 1: Get an instance of JanusGraph.

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

Step 2: Create a new vertex in the graph with the vertex label.

JanusGraphVertex janusGraphVertex = janusGraph.addVertex("person");

Step 3: Attach properties to the vertex.

janusGraphVertex.property("name", "Krishna");
janusGraphVertex.property("age", 31);
janusGraphVertex.property("gender", 'M');

Step 4: Commit the transaction.

janusGraph.tx().commit();

Find the below working application.

 

AddVertex.java

package com.sample.app.vertex;

import java.util.Iterator;
import java.util.Set;

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

public class AddVertex {

	public static void main(String args[]) {

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

		// Create a person vertex
		JanusGraphVertex janusGraphVertex = janusGraph.addVertex("person");

		// Add properties to the vertex
		janusGraphVertex.property("name", "Krishna");
		janusGraphVertex.property("age", 31);
		janusGraphVertex.property("gender", 'M');

		janusGraph.tx().commit();

		Iterator<Vertex> janusGraphVertexes = janusGraph.vertices(janusGraphVertex.id());
		Vertex vertex = janusGraphVertexes.next();

		System.out.println("-----------------------------");
		System.out.println("id : " + vertex.id());
		System.out.println("long id : " + ((JanusGraphVertex) vertex).longId());
		System.out.println("label : " + vertex.label());

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

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

}

Output

-----------------------------
id : 4184
long id : 4184
label : person
properties
	gender -> M
	name -> Krishna
	age -> 31
-----------------------------
Done!!!








 

 

Previous                                                 Next                                                 Home

Saturday, 29 January 2022

Exploring JanusGraphVertex

 

            JanusGraph: Create a vertex
            JanusGraph: Get the vertex by id
            JanusGraph: Get the vertex properties
            JanusGraph: id vs longid
            What is the default label of a vertex in JanusGraph?
            JanusGraph: Add a label to vertex
            JanusGraph: Create edge between vertexes
            JanusGraph: Add multiple values to a vertex property
            JanusGraph: Get the vertex Property object by property name
            JanusGraph: Add properties to a vertex property
            JanusGraph: Get all the edges of this vertex

Previous                                                 Next                                                 Home

JanusGraph: Disable debug log

When I am running janusgraph application, I end up in lot of debug log messages, I resolved this issue by configuring logback.xml file in the application resources folder.

 

logback.xml

<configuration scan="true">


	<appender name="STDOUT"
		class="ch.qos.logback.core.ConsoleAppender">
		<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
			<level>ERROR</level>
		</filter>
		<encoder>
			<pattern>%-5level [%thread] %date{ISO8601} %F:%L - %msg%n</pattern>
		</encoder>
	</appender>


	<root level="ERROR">
		<appender-ref ref="STDOUT" />
	</root>

</configuration>

 

Reference

https://github.com/JanusGraph/janusgraph/blob/83c93fe717453ec31086ca1a208217a747ebd1a8/janusgraph-dist/src/assembly/static/cassandra/conf/logback.xml

 

  

Previous                                                 Next                                                 Home

Janus Graph core entities

 

There are two basic entities in Janusgraph.

a.   JanusGraphVertex : Represent a vertex in JanusGraph. A vertex have edges and properties.

b.   JanusGraphRelation: Represent the relation between a vertex and other entity. JanusGraphVertexProperty and JanusGraphEdge extend JanusGraphRelation.

1.   JanusGraphEdge: Connect two JanusGraphVertex objects.

2.   JanusGraphVertexProperty: It is a JanusGraphRelation connecting a vertex to a value.


Previous                                                 Next                                                 Home

Exploring janusgraph core library

Dependencies used.


	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.janusgraph/janusgraph-core -->
		<dependency>
			<groupId>org.janusgraph</groupId>
			<artifactId>janusgraph-core</artifactId>
			<version>0.6.1</version>
		</dependency>

		<dependency>
			<groupId>org.janusgraph</groupId>
			<artifactId>janusgraph-cql</artifactId>
			<version>0.6.1</version>
		</dependency>


		<dependency>
			<groupId>io.netty</groupId>
			<artifactId>netty-all</artifactId>
			<version>4.1.73.Final</version>
		</dependency>

	</dependencies>

You can download all the examples of this tutorial series from below link.

https://github.com/harikrishna553/java-libs/tree/master/janus-graph-demo


Previous                                                 Next                                                 Home