SpringBoot XML RestAPIs + MongoDB – Post/Get/Put/Delete Requests Example

springboot-xml-restapi-mongodb---feature-image

In the tutorial, Grokonez show you how to create SpringBoot XML RestAPIs and MongoDB with Post/Get/Put/Delete requests using jaxb-api & jackson-dataformat-xml

Related posts:
How to build SpringBoot MongoDb RestfulApi

Technologies

– SpringBoot
– MongoDB
– Postman Rest-Client

Practices

Project Structure ->

springboot-xml-restapi-mongodb---spring-boot-project

Create SpringBoot project

– We use SpringToolSuite to create a SpringBoot project with below dependencies:


	org.springframework.boot
	spring-boot-starter-web



	org.springframework.boot
	spring-boot-starter-data-mongodb



	com.fasterxml.jackson.dataformat
	jackson-dataformat-xml

      

	javax.xml.bind
	jaxb-api
	2.3.1

– The jackson-dataformat-xml adds Jackson XML serializer and deserializer.

Model

– We use @JacksonXmlRootElement & @JacksonXmlProperty to create Customer.java model:

  • @JacksonXmlProperty is used to set an attribute of the element in the XML output.
  • @JacksonXmlRootElement is used to set the name for the XML output root element.
package com.grokonez.xmlrestapi.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

@Document(collection = "customers")
@JacksonXmlRootElement(localName = "Customer")
public class Customer {
    @Id
    @JacksonXmlProperty(isAttribute = true)
    private String id;

    @JacksonXmlProperty    
	private String firstname;
 
    @JacksonXmlProperty
	private String lastname;
    
    @JacksonXmlProperty
    private int age;

    public Customer() {
    }

    public Customer(String id, String firstname, String lastname, int age) {
        this.id = id;
        this.firstname = firstname;
        this.lastname = lastname;
        this.age = age;
    }

    public String getId() {
        return id;
    }

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

    public String getFirstname() {
    	return firstname;
    }
    
    public void setFirstname(String firstName) {
    	this.firstname = firstName;
    }
    
    public String getLastname() {
    	return this.lastname;
    }
    
    public void setLastname(String lastName) {
    	this.lastname = lastName;
    }
    
    public int getAge() {
    	return this.age;
    }
    
    public void setAge(int age) {
    	this.age = age;
    }
}

– Create an Customers.java helper class:

package com.grokonez.xmlrestapi.model;

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

@JacksonXmlRootElement
public class Customers{

    @JacksonXmlProperty(localName = "Customers")
    @JacksonXmlElementWrapper(useWrapping = false)
    private List customers = new ArrayList();

    public List getCustomers() {
        return customers;
    }

    public void setCustomers(List customers) {
        this.customers = customers;
    }
}

-> We use @JacksonXmlProperty & @JacksonXmlElementWrapper annotations to set a list of Customer to be elements of Customers element in XML output.

JPA Repository

– Create JPA repository CustomerRepository.java ->

package com.grokonez.xmlrestapi.repository;

import org.springframework.data.mongodb.repository.MongoRepository;

import com.grokonez.xmlrestapi.model.Customer;

public interface CustomerRepository extends MongoRepository{
}
Controller RestAPIs

– We create 4 RestAPIs with Post/Get/Put/Delete XML request-mapping:

package com.grokonez.xmlrestapi.controller;

import java.util.List;
import java.util.Optional;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.grokonez.xmlrestapi.model.Customer;
import com.grokonez.xmlrestapi.model.Customers;
import com.grokonez.xmlrestapi.repository.CustomerRepository;

@RestController
@RequestMapping("/api")
public class CustomerRestAPIs {
	
    @Autowired
    private CustomerRepository customerRepository;

    @PostMapping(value="/customer", produces=MediaType.APPLICATION_XML_VALUE)
	public Customer postCustomer(@RequestBody Customer customer) {
		return customerRepository.save(customer);
	}
    
    @GetMapping(value="/customer", produces=MediaType.APPLICATION_XML_VALUE)
    public Customers getAllCustomers() {
        List customer = (List) customerRepository.findAll();
        Customers customers = new Customers();
        customers.setCustomers(customer);

        return customers;
    }
    
    @GetMapping(value="/customer/{id}", produces=MediaType.APPLICATION_XML_VALUE)
    public Customer getCustomerById(@PathVariable Long id) {
    	Optional optCustomer = customerRepository.findById(id);
    	
    	if(optCustomer.isPresent()) {
    		return customerRepository.findById(id).get();
    	}
    	
    	throw new RuntimeException("Not Found a customer with id = " + id);
    }
    
    @PutMapping(value="/customer/{id}", produces=MediaType.APPLICATION_XML_VALUE)
    public Customer putCustomer(@PathVariable Long id,
            @Valid @RequestBody Customer customerUpdated) {
    	
    	return customerRepository.findById(id)
    			.map(customer -> {
                    customer.setFirstname(customerUpdated.getFirstname());
                    customer.setLastname(customerUpdated.getLastname());
                    customer.setAge(customerUpdated.getAge());
                    return  customerRepository.save(customer);
                }).orElseThrow(() -> new RuntimeException("Customer not found with id = " + id));
    }
    
    @DeleteMapping("/customer/{id}")
    public String deleteCustomer(@PathVariable Long id) {
        return customerRepository.findById(id)
                .map(customer -> {
                    customerRepository.delete(customer);
                    return "Delete Successfully!";
                }).orElseThrow(() -> new RuntimeException("Customer not found with id = " + id));
    }
}

-> With MediaType.APPLICATION_XML_VALUE, Spring uses a message converter to produces XML data.

Application configuration

– Open file application.properties, add configuration:

spring.data.mongodb.database=gkzdb
spring.data.mongodb.port=27017
Run & Check Results

– Run SpringBoot application & start MongoDB database.

-> Make post requests:

springboot-xml-restapi-mongodb---save-a-customer

springboot-xml-restapi-mongodb---save-all-mongodb-records

-> Get customers:

springboot-xml-restapi-mongodb---get-a-customer

springboot-xml-restapi-mongodb---get-all-mongodb

-> Put a customer:

springboot-xml-restapi-mongodb---put-a-customer

springboot-xml-restapi-mongodb---put-a-customer-mongodb-record

– Delete a customer:

springboot-xml-restapi-mongodb---delete-a-customer

springboot-xml-restapi-mongodb---delete-a-customer-mongodb-records

Sourcecode

SpringBootXMLRestAPI



By grokonez | January 20, 2019.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*