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.ozenero.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.ozenero.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.ozenero.xmlrestapi.repository;

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

import com.ozenero.xmlrestapi.model.Customer;

public interface CustomerRepository extends MongoRepository{
}
Controller RestAPIs

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

package com.ozenero.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.ozenero.xmlrestapi.model.Customer;
import com.ozenero.xmlrestapi.model.Customers;
import com.ozenero.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

18 thoughts on “SpringBoot XML RestAPIs + MongoDB – Post/Get/Put/Delete Requests Example”

  1. Admiring the time and effort you put into your site and detailed information you present.
    It’s awesome to come across a blog every once in a while that isn’t the same unwanted rehashed information. Great read!
    I’ve bookmarked your site and I’m adding your
    RSS feeds to my Google account.

  2. My partner and I absolutely love your blog and find nearly
    all of your post’s to be just what I’m looking for.
    Do you offer guest writers to write content for yourself?
    I wouldn’t mind writing a post or elaborating on a few of the subjects you write about here.

    Again, awesome website!

  3. Hi there, just became aware of your blog through Google, and found that it’s really informative.
    I am gonna watch out for brussels. I’ll be grateful if you continue this in future.
    A lot of people will be benefited from your writing.
    Cheers!

  4. I loved as much as you’ll receive carried out right here.
    The sketch is attractive, your authored subject matter stylish.
    nonetheless, you command get bought an edginess over that you wish be delivering the following.
    unwell unquestionably come more formerly again as exactly the same
    nearly very often inside case you shield this hike.

  5. I absolutely love your blog and find almost all of your post’s to be what precisely I’m looking
    for. Do you offer guest writers to write content for
    yourself? I wouldn’t mind producing a post or elaborating on a few of the subjects you write related to here.
    Again, awesome blog!

  6. My brother recommended I might like this web site.
    He was totally right. This post truly made my day. You
    can not imagine just how much time I had spent for this info!
    Thanks!

  7. I am curious to find out what blog system you’re working with?
    I’m experiencing some minor security problems with my
    latest site and I would like to find something more safe. Do you have any suggestions?

  8. Appreciating the time and energy you put into your website and in depth information you offer.

    It’s great to come across a blog every once in a while that isn’t the same unwanted rehashed material.

    Great read! I’ve saved your site and I’m adding your RSS feeds to my Google account.

  9. magnificent points altogether, you simply gained a new reader.
    What would you suggest about your put up that you just made some days
    in the past? Any certain?

  10. After looking over a number of the articles on your site, I truly like your technique of writing a
    blog. I added it to my bookmark site list and will be checking
    back in the near future. Take a look at my web site as well and let
    me know how you feel.

  11. When I initially left a comment I seem to have clicked the -Notify
    me when new comments are added- checkbox and now each time a comment is added I recieve four emails with the same comment.
    Is there a means you are able to remove me from
    that service? Appreciate it!

  12. You could certainly see your expertise within the work you write.
    The arena hopes for more passionate writers like
    you who are not afraid to mention how they believe. Always follow
    your heart.

  13. 434883 94917This is the fitting weblog for anybody who desires to locate out about this subject. You notice a lot its practically onerous to argue with you (not that I truly would wantHaHa). You undoubtedly put a brand new spin on a subject thats been written about for years. Good stuff, merely wonderful! 441904

Leave a Reply

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