Tuesday, 2 November 2021

Spring Data: ArangoDB: update an entity

‘save’ method of repository interface is used to update an entity.

 

Example

Optional<Employee> empOpt = employeeRepo.findById(emp1.getArangoId());

if (!empOpt.isPresent()) {
  System.out.println("Employee with given id is not present");
} else {
  emp1.setFirstName("Rama Krishna");
  emp1.setLastName("Majety");

  emp1 = employeeRepo.save(emp1);

  System.out.println("emp1 is updated, persisted data : " + emp1);
}

Find the below working application.

 

Step 1: Create new maven project ‘update-entity-demo’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sample.app</groupId>
  <artifactId>update-entity-demo</artifactId>
  <version>1</version>

  <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.5</version>
  </parent>


  <dependencies>
    <dependency>
      <groupId>com.arangodb</groupId>
      <artifactId>arangodb-spring-boot-starter</artifactId>
      <version>2.3.3.RELEASE</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>


Step 3: Define entity class.

 

Employee.java

package com.sample.app.entity;

import com.arangodb.springframework.annotation.ArangoId;
import com.arangodb.springframework.annotation.Document;
import org.springframework.data.annotation.Id;

@Document("employees")
public class Employee {

  @Id // db document field: _key
  private String key;

  @ArangoId // db document field: _id
  private String arangoId;

  private Integer id;
  private String firstName;
  private String lastName;

  public Employee(Integer id, String firstName, String lastName) {
    super();
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
  }

  public String getKey() {
    return key;
  }

  public void setKey(String key) {
    this.key = key;
  }

  public String getArangoId() {
    return arangoId;
  }

  public void setArangoId(String arangoId) {
    this.arangoId = arangoId;
  }

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  @Override
  public String toString() {
    return "Employee [key=" + key + ", arangoId=" + arangoId + ", id=" + id + ", firstName=" + firstName
        + ", lastName=" + lastName + "]";
  }

}


Step 4: Define Repository interface.

 

EmployeeRepository.java

package com.sample.app.repository;

import com.arangodb.springframework.repository.ArangoRepository;
import com.sample.app.entity.Employee;

public interface EmployeeRepository extends ArangoRepository<Employee, String> {

}


Step 5: Define Arango configuration class.

 

ArangoConfig.java

package com.sample.app.config;

import com.arangodb.ArangoDB;
import com.arangodb.springframework.annotation.EnableArangoRepositories;
import com.arangodb.springframework.config.ArangoConfiguration;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableArangoRepositories(basePackages = { "com.sample.app" })
public class ArangoConfig implements ArangoConfiguration {

  @Override
  public ArangoDB.Builder arango() {
    return new ArangoDB.Builder().host("localhost", 8529).user("root").password("tiger");
  }

  @Override
  public String database() {
    return "abc_org";
  }
}


Step 6: Define main application class.

 

App.java

package com.sample.app;

import java.util.Optional;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.sample.app.entity.Employee;
import com.sample.app.repository.EmployeeRepository;

@SpringBootApplication
public class App {
  public static void main(String args[]) {
    SpringApplication.run(App.class, args);
  }

  @Bean
  public CommandLineRunner demo(EmployeeRepository employeeRepo) {
    return (args) -> {

      Employee emp1 = new Employee(1, "Ram", "Gurram");

      emp1 = employeeRepo.save(emp1);

      System.out.println("emp1 is persisted to employees collection, persisted data : " + emp1);

      Optional<Employee> empOpt = employeeRepo.findById(emp1.getArangoId());

      if (!empOpt.isPresent()) {
        System.out.println("Employee with given id is not present");
      } else {
        emp1.setFirstName("Rama Krishna");
        emp1.setLastName("Majety");

        emp1 = employeeRepo.save(emp1);

        System.out.println("emp1 is updated, persisted data : " + emp1);
      }

    };
  }
}


Total project structure looks like below.





Run App.java, you will see below messages in console.


emp1 is persisted to employees collection, persisted data : Employee [key=71869, arangoId=employees/71869, id=1, firstName=Ram, lastName=Gurram]
emp1 is updated, persisted data : Employee [key=71869, arangoId=employees/71869, id=1, firstName=Rama Krishna, lastName=Majety]


You can download the complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/arangodb/update-entity-demo



 

 

Previous                                                    Next                                                    Home

Pydantic: @root_validator: Apply validation on entire model

‘@root_validator’ is used to apply validation on entire model.

 

root_validator_1.py

from pydantic import (
    BaseModel, 
    ValidationError, 
    validator,
    root_validator
)

from typing import Optional

class Box(BaseModel):
    id: int
    weight: int = None
    height: int = None

    @root_validator
    def allValidator(cls, values):
        if(values == None):
            raise ValueError('id, weight and height must set to a value')

        idTemp = values.get('id')
        weightTemp = values.get('weight')
        heightTemp = values.get('height')

        err = '';
        if(idTemp < 1):
            err = err + 'id must > 0. '

        if(weightTemp < 10):
            err = err + 'weigh must >= 10. '

        if(heightTemp < 15):
            err = err + 'height must >= 15'

        if(len(err) > 1):
            raise ValueError(err)

        return values

try:
    b1 = Box(id = -1, weight = 0, height=16)
    print(b1)
except ValidationError as e:
    print(e.json())

 

Output

[
  {
    "loc": [
      "__root__"
    ],
    "msg": "id must > 0. weigh must >= 10. ",
    "type": "value_error"
  }
]

 


 

Previous                                                    Next                                                    Home

FastAPI: enum: Specify predefined values to path parameter

Using standard python Enum, we can specify predefined values to the path parameter.

 

Step 1: Define an enum.

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

 

Step 2: Use the enum while defining path parameter.

@app.get("/emps/by-country/{countryName}")
def empByCountryName(countryName: CountryEnum):
    empsTemp = []

    for empId in emps:
        if (emps[empId]["country"] == countryName.name):
            empsTemp.append(emps[empId])
    return empsTemp

Find the below working application.

 

main.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

class EmployeeUpdateDto(BaseModel):
    name: Optional[str]
    age : Optional[int]
    country: Optional[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/self")
def self():
    return {'name' : 'Krishna', 'age' : 32, 'country' : 'russia'}
    
@app.get("/emps/by-id/{empId}")
def empById(empId: int = Path(None, description = "Enter valid employee id", gt = 0, lt = 3)):
    if(empId in emps):
        return emps[empId]
    else:
        raise Exception("Employee not exist with given id " + str(empId))

@app.get("/emps/by-name")
def empByName(name: Optional[str] = None):
    if name == None:
        return {"message" : "no input provided"}
    
    empsTemp = []
    for empId in emps:
        if emps[empId]["name"] == name:
            empsTemp.append(emps[empId])
    return empsTemp

@app.get("/emps/by-country/{countryName}")
def empByCountryName(countryName: CountryEnum):
    empsTemp = []

    for empId in emps:
        if (emps[empId]["country"] == countryName.name):
            empsTemp.append(emps[empId])
    return empsTemp

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

@app.put("/emps/by-id/{empId}")
def updateEmployee(empId : int, emp: EmployeeUpdateDto):
    if(empId not in emps):
        return {"message" : "Not found"}
    
    persistedEmp = emps[empId]

    if(emp.name != None):
        persistedEmp["name"] = emp.name
    
    if(emp.age != None):
        persistedEmp["age"] = emp.age

    if(emp.country != None):
        persistedEmp["country"] = emp.country

    return {"id" : empId, "name" : persistedEmp["name"], "age": persistedEmp["age"], "country" : persistedEmp["country"]}

@app.delete("/emps/by-id/{empId}")
def deleteEmpById(empId: int = Path(None, description = "Enter valid employee id")):
    if(empId in emps):
        del emps[empId]
        return {"msg" : "Employee is deleted with given id " + str(empId)}
    else:
        return {"msg" : "Employee not exist with given id " + str(empId)}


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

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


Open the url ‘http://127.0.0.1:8000/docs’ in browser.

 

Expand the endpoint '/emps​/by-country​/{countryName}', you will see a list of possible values for the countryName path parameter.



What happen if I pass a path parameter that is not in the predefined list?

You will get a validation error, refer below screenshot.

 


 

 

Previous                                                    Next                                                    Home

FastAPI: Order matter while defining path parameter

Path operations are evaluated in the order they defined.  In case, if you have fixed paths in the path definitions, define them prior to the variable paths.

 

For example,

@app.get("/emps/by-id/self")
def self():
    return {'name' : 'Krishna', 'age' : 32}
    
@app.get("/emps/by-id/{empId}")
def empById(empId: int = Path(None, description = "Enter valid employee id", gt = 0, lt = 3)):
    if(empId in emps):
        return emps[empId]
    else:
        raise Exception("Employee not exist with given id " + str(empId))

 

As you see above snippet, I have a path ‘/emps/by-id/self’ to describe self, and ‘/emps/by-id/{empId}’ to get the data about an employee by id. Since path operations evaluate in order, you should make sure that the path for ‘/emps/by-id/self’ is declared before the one for ‘/emps/by-id/{empId}’.

 

Otherwise empId is matched to the value ‘self’ and you will get below validation error.

 

{"detail":[{"loc":["path","empId"],"msg":"value is not a valid integer","type":"type_error.integer"}]}

 

Find the below working application.

 

main.py

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

app = FastAPI()

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

class EmployeeUpdateDto(BaseModel):
    name: Optional[str]
    age : Optional[int]

# employees information
emps = {
    1 : {
        "name" : "Krishna",
        "age": 32
    },
    2 : {
        "name" : "Ram",
        "age": 33
    }
}

# 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/self")
def self():
    return {'name' : 'Krishna', 'age' : 32}
    
@app.get("/emps/by-id/{empId}")
def empById(empId: int = Path(None, description = "Enter valid employee id", gt = 0, lt = 3)):
    if(empId in emps):
        return emps[empId]
    else:
        raise Exception("Employee not exist with given id " + str(empId))

@app.get("/emps/by-name")
def empByName(name: Optional[str] = None):
    if name == None:
        return {"message" : "no input provided"}
    for empId in emps:
        if emps[empId]["name"] == name:
            return emps[empId]
    return {"message" : "Not found"}

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

@app.put("/emps/by-id/{empId}")
def updateEmployee(empId : int, emp: EmployeeUpdateDto):
    if(empId not in emps):
        return {"message" : "Not found"}
    
    persistedEmp = emps[empId]

    if(emp.name != None):
        persistedEmp["name"] = emp.name
    
    if(emp.age != None):
        persistedEmp["age"] = emp.age

    return {"id" : empId, "name" : persistedEmp["name"], "age": persistedEmp["age"]}

@app.delete("/emps/by-id/{empId}")
def deleteEmpById(empId: int = Path(None, description = "Enter valid employee id")):
    if(empId in emps):
        del emps[empId]
        return {"msg" : "Employee is deleted with given id " + str(empId)}
    else:
        return {"msg" : "Employee not exist with given id " + str(empId)}

 

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

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

Open the url ‘http://127.0.0.1:8000/emps/by-id/self’ in browser, you will see below kind of output.



Open the url ‘http://127.0.0.1:8000/emps/by-id/2’ in browser, you will see below screen.

 


 

 

 

Previous                                                    Next                                                    Home

Pydantic: validate always

If a field do not set any value, then pydantic validator is not called on that field. You can customize this behaviour by passing the argument ‘always=True’.

 

validator_demo_6.py

from pydantic import BaseModel, ValidationError, validator
from typing import Optional

class Box(BaseModel):
    id: int
    weight: int = None
    height: int = None

    @validator('*', always=True)
    def allValidator(cls, value):
        if(value == None):
            raise ValueError('id, weight and height must set to a value')
        if(value < 1):
            raise ValueError('id, weight and height must > 0')
        return value

try:
    b1 = Box(id = 1, weight = 0)
    print(b1)
except ValidationError as e:
    print(e.json())

 

Output

[
  {
    "loc": [
      "weight"
    ],
    "msg": "id, weight and height must > 0",
    "type": "value_error"
  },
  {
    "loc": [
      "height"
    ],
    "msg": "id, weight and height must set to a value",
    "type": "value_error"
  }
]

 


Previous                                                    Next                                                    Home