Wednesday, 1 December 2021

Spring rest: void controller method

In this post, I am going to explain how to design void controller method. Void controller methods are useful, when you do not want to send any response body.

 

Just by returning the ResponseEntity with appropriate headers, we can address this usecase.

 

Example

@GetMapping(value = "/health")
@ResponseStatus(value = HttpStatus.OK)
public void updateDataThatDoesntRequireClientToBeNotified() {
	System.out.println("Request received to check application health");
}

 

Find the below working application.

 

Step 1: Create new maven project ‘void-controller-method’.

 

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>void-controller-method</artifactId>
	<version>1</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.5.6</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>


	<dependencies>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>


	</dependencies>

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

 

Step 3: Define HelloController class.

 

HelloController.java

package com.sample.app.controller;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

	@GetMapping(value = "/health")
	@ResponseStatus(value = HttpStatus.OK)
	public void updateDataThatDoesntRequireClientToBeNotified() {
		System.out.println("Request received to check application health");
	}
}

 

Step 4: Define main application class.

 

App.java

package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

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

}

 

Total project structure looks like below.



Run App.java.

 

Open the url ‘http://localhost:8080/health’ in browser, you can observe response code value as 200.

 



You can download complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/rest/void-controller-method


 

  

Previous                                                    Next                                                    Home

Spring Data: ArangoTemplate: Create multiple documents

ArangoOperations interface provides insert method to insert multiple documents.

 

Signature

<T> MultiDocumentEntity<? extends DocumentEntity> insert(Iterable<T> values, Class<T> entityClass, DocumentCreateOptions options) throws DataAccessException;

<T> MultiDocumentEntity<? extends DocumentEntity> insert(Iterable<T> values, Class<T> entityClass) throws DataAccessException;

 

Creates new documents from the given documents, unless there is already a document with the _key given. If no _key is given, a new unique _key is generated automatically.

 

‘DocumentCreateOptions’ parameter is used to provide additional options while creating the documents.

 

Following table summarizes different options that are provided using ‘DocumentCreateOptions’.

 

Option

Datatype

Description

waitForSync

Boolean

If it is set to true, ArangoDB waits until the document is synced to disk.

returnNew

Boolean

If this is set to true, then this method return the newly created document.

returnOld

Boolean

If this is set tot true, then this return the complete old document under the attribute old in the result.

overwrite

Boolean

If it is set true and the document with given key is already exists, then insert method replace the document

overwriteMode

OverwriteMode

OverwriteMode is an enum with 4 possible values.

a.   ignore: if a document with the specified _key value exists already, nothing will be done and no write operation will be carried out. Insert operation just return success in this case.

b.   replace: if a document with the specified _key value exists already, it will be overwritten with the specified document value. This mode will also be used when no overwrite mode is specified but the overwrite flag is set to true.

c.    update: if a document with the specified _key value exists already, it will be patched (partially updated) with the specified document value.

d.   conflict: if a document with the specified _key value exists already, return a unique constraint violation error so that the insert operation fails. This is also the default behavior in case the overwrite mode is not set, and the overwrite flag is false or not set either.

silent

Boolean

If it is set to true, an empty object is returned as part of the response (no response from server).

streamTransactionId

String

If set, the operation will be executed within the transaction.

mergeObjects

Boolean

Controls whether objects (not arrays) will be merged if present in both the existing and the patch  document. If set to false, the value in the patch document will overwrite the existing document's value. If set to true, objects will be merged. The default is true.

 

Example

MultiDocumentEntity<DocumentCreateEntity> multiDocuments = (MultiDocumentEntity<DocumentCreateEntity>) arangoTemplate.insert(Arrays.asList(emp1, emp2, emp3), Employee.class, docCreateOptions);

 

Find the below working application.

 

Step 1: Create new maven project ‘arango-template-create-documents’.

 

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>arango-template-create-documents</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 Employee entity class.

 

Employee.java

 

package com.sample.app.entity;

import org.springframework.data.annotation.Id;

import com.arangodb.springframework.annotation.ArangoId;
import com.arangodb.springframework.annotation.Document;

@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;
	private Integer age;

	public Employee() {

	}

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

	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;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

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

}

 

Step 4: Define arango db configuration class.

 

ArangoConfig.java

package com.sample.app.config;

import org.springframework.context.annotation.Configuration;

import com.arangodb.ArangoDB;
import com.arangodb.springframework.annotation.EnableArangoRepositories;
import com.arangodb.springframework.config.ArangoConfiguration;

@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 5: Define main application class.

 

App.java

 

package com.sample.app;

import java.util.Arrays;
import java.util.Collection;

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

import com.arangodb.entity.DocumentCreateEntity;
import com.arangodb.entity.MultiDocumentEntity;
import com.arangodb.model.DocumentCreateOptions;
import com.arangodb.springframework.core.ArangoOperations;
import com.sample.app.entity.Employee;

@SpringBootApplication
public class App {

	@Autowired
	private ArangoOperations arangoTemplate;

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

	@Bean
	public CommandLineRunner demo() {

		return (args) -> {

			Employee emp1 = new Employee(1, "Ram", "Gurram", 31);
			Employee emp2 = new Employee(2, "Sailaja", "Ptr", 33);
			Employee emp3 = new Employee(3, "Sravya", "Y", 85);

			DocumentCreateOptions docCreateOptions = new DocumentCreateOptions();
			docCreateOptions.returnNew(true);

			MultiDocumentEntity<DocumentCreateEntity> multiDocuments = (MultiDocumentEntity<DocumentCreateEntity>) arangoTemplate
					.insert(Arrays.asList(emp1, emp2, emp3), Employee.class, docCreateOptions);

			Collection<DocumentCreateEntity> documentCreateEntities = multiDocuments.getDocuments();

			System.out.println("Created documents");
			for (DocumentCreateEntity docCreateEntity : documentCreateEntities) {
				System.out.println("\nid : " + docCreateEntity.getId());
				System.out.println("key : " + docCreateEntity.getKey());
				System.out.println("revision : " + docCreateEntity.getRev());
				System.out.println("doc : " + docCreateEntity.getNew());
			}

		};
	}
}

Total project structure looks like below.

 


 

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

<pre class="hljs" style="display: block; overflow-x: auto; padding: 0.5em; background: rgb(240, 240, 240) none repeat scroll 0% 0%; color: rgb(68, 68, 68);">Created documents

id : employees/33132
key : 33132
revision : _cUk_MiS---
doc : {"_key":"33132","_id":"employees<span class="hljs-tag">\<span class="hljs-name" style="font-weight: 700;">/</span></span>33132","_rev":"_cUk_MiS---","id":1,"firstName":"Ram","lastName":"Gurram","age":31,"_class":"com.sample.app.entity.Employee"}

id : employees/33133
key : 33133
revision : _cUk_MiS--A
doc : {"_key":"33133","_id":"employees<span class="hljs-tag">\<span class="hljs-name" style="font-weight: 700;">/</span></span>33133","_rev":"_cUk_MiS--A","id":2,"firstName":"Sailaja","lastName":"Ptr","age":33,"_class":"com.sample.app.entity.Employee"}

id : employees/33134
key : 33134
revision : _cUk_MiS--C
doc : {"_key":"33134","_id":"employees<span class="hljs-tag">\<span class="hljs-name" style="font-weight: 700;">/</span></span>33134","_rev":"_cUk_MiS--C","id":3,"firstName":"Sravya","lastName":"Y","age":85,"_class":"com.sample.app.entity.Employee"}
</pre>

You can download complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/arangodb/arango-template-create-documents



Previous                                                    Next                                                    Home

FastAPI: Send multiple body payloads

FastAPI allows you to declare multiple body payloads.

 

Example

@app.post("/emps")
def createEmployee(emp: Employee, address: Address)

 In the above example, FastAPI will notice that there are more than one body parameters in the function. So, it will then use the parameter names as keys (field names) in the body, and expect a body like below. 

{
  "emp": {
    "name": "PTR",
    "age": 33
  },
  "address": {
    "street": "CH street",
    "city": "Delhi"
  }
}

 

FastAPI will do the automatic conversion from the request, so that the parameter ‘emp’ receives it's specific content and the same for ‘address’.

 

Find the below working application.

 

multipleBodyParams.py

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

app = FastAPI()

# employees information
emps = {
    1 : {
        "name" : "Krishna",
        "age": 32,
        "address": {
            "street" : "Chowdeswari",
            "city" : "Bangalore"
        }
    }
}

class Employee(BaseModel):
    name: str
    age : int

class Address(BaseModel):
    street: str
    city: str

@app.get("/emps")
def allEmployees():
    return emps

@app.post("/emps")
def createEmployee(emp: Employee, address: Address):
    noOfEmps = len(emps)
    newId = noOfEmps + 1
    emps[newId] = dict(emp)
    emps[newId]['address'] = dict(address)

    return {
        "id" : newId, 
        "name" : emps[newId]['name'], 
        "age": emps[newId]['age'],
        "address" : emps[newId]['address']
        }

 

Open terminal and execute the command ‘uvicorn multipleBodyParams:app –reload’.

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

 

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

 


 

 

Previous                                                    Next                                                    Home

Python: bytearray: Return mutable array of bytes

‘bytearray’ method take an object and return a mutable bytes array.

 

Signature

bytearray([source[, encoding[, errors]]])

 

byte_array_1.py

even_numbers = [2, 4, 6, 8]

byte_array = bytearray(even_numbers)
print(byte_array)

 

Output

bytearray(b'\x02\x04\x06\x08')

 

 

  

Previous                                                    Next                                                    Home