DZone

  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
  • Manage My Drafts

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Containers Trend Report: Explore the current state of containers, containerization strategies, and modernizing architecture.

DZone Kubernetes Research: We want to hear about your K8s experience and insights — join us for our 5th annual survey (and enter to win $$).

  • Your Guide to GraphQL [Tutorials and Articles]
  • Building REST API Backend Easily With Ballerina Language
  • How to Automate Restful APIs Using Jayway Library
  • Choosing a Library to Build a REST API in Java
  • Introducing Klone: Open-Source Remote debugging Tool for Kubernetes Services
  • Top 10 Microservices Frameworks
  • Send Your Logs to Loki
  • A Guide To Taming Blocking Operations With Project Reactor
  • Data Engineering

Build a REST API with XML Payload

Creating rest apis with xml payloads..

Neerav Aggarwal user avatar

Join the DZone community and get the full member experience.

There is hardly any argument on the fact that APIs are increasingly becoming an important part of how companies do business. API has become the de facto standard to unlock one of their most valuable resources, data.

And as organizations are publishing more APIs , the observed trend is that REST is replacing SOAP as the data transfer protocol of choice. When it comes to the data that APIs serve up, XML is still the most used format. Although JSON is hot on its heels, we still need to address plenty of use cases with  XML payload.

In this post, we will go step by step through an example to build out a RESTful web service with XML request and response payload. Check out the complete project on Anypoint Exchange .

Pre-requisites:

  • Sign up for an Anypoint Platform Account .
  • Download Anypoint Platform Design Tool –  MuleSoft  Anypoint Studio . In this post, we are using version 5.4 of Anypoint Studio with the new “Studio Light Theme”. You can always revert to the old theme in Preferences.
  • A database where we can create and load a sample table required for this project. In this example, we will use an instance of the  MySQL database .
  • To follow the example in this guide, run the SQL script customer.sql to set up the table and load it with some sample data.

You can download this complete project from Anypoint Exchange .

In this post and from our previous post we have understood how easy it is to create an API with the end user in mind.

The trends suggest the shift towards RESTful APIs but the decision of the data format between JSON or XML is still fifty-fifty. In any case, we can have either or both data formats in our API repository.

In the next post, we will see how we can configure composite processes by utilizing multiple APIs with both JSON and XML data formats.

Published at DZone with permission of Neerav Aggarwal . See the original article here.

Opinions expressed by DZone contributors are their own.

Partner Resources

  • About DZone
  • Send feedback
  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Become a Contributor
  • Visit the Writers' Zone
  • Terms of Service
  • Privacy Policy
  • 600 Park Offices Drive
  • Durham, NC 27709
  • [email protected]

Let's be friends:

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Using XMLHttpRequest

In this guide, we'll take a look at how to use XMLHttpRequest to issue HTTP requests in order to exchange data between the website and a server.

Examples of both common and more obscure use cases for XMLHttpRequest are included.

To send an HTTP request, create an XMLHttpRequest object, open a URL, and send the request. After the transaction completes, the object will contain useful information such as the response body and the HTTP status of the result.

Types of requests

A request made via XMLHttpRequest can fetch the data in one of two ways, asynchronously or synchronously. The type of request is dictated by the optional async argument (the third argument) that is set on the XMLHttpRequest.open() method. If this argument is true or not specified, the XMLHttpRequest is processed asynchronously, otherwise the process is handled synchronously. A detailed discussion and demonstrations of these two types of requests can be found on the synchronous and asynchronous requests page. You can't use synchronous requests outside web workers as it freezes the main interface.

Note: The constructor XMLHttpRequest isn't limited to only XML documents. It starts with "XML" because when it was created the main format that was originally used for asynchronous data exchange was XML.

Handling responses

There are several types of response attributes defined for the XMLHttpRequest() constructor. These tell the client making the XMLHttpRequest important information about the status of the response. Some cases where dealing with non-text response types may involve some manipulation and analysis are outlined in the following sections.

Analyzing and manipulating the responseXML property

If you use XMLHttpRequest to get the content of a remote XML document, the responseXML property will be a DOM object containing a parsed XML document. This could prove difficult to manipulate and analyze. There are four primary ways of analyzing this XML document:

  • Using XPath to address (or point to) parts of it.
  • Manually Parsing and serializing XML to strings or objects.
  • Using XMLSerializer to serialize DOM trees to strings or to files .
  • RegExp can be used if you always know the content of the XML document beforehand. You might want to remove line breaks, if you use RegExp to scan with regard to line breaks. However, this method is a "last resort" since if the XML code changes slightly, the method will likely fail.

Note: XMLHttpRequest can now interpret HTML for you using the responseXML property. Read the article about HTML in XMLHttpRequest to learn how to do this.

Processing a responseText property containing an HTML document

If you use XMLHttpRequest to get the content of a remote HTML webpage, the responseText property is a string containing the raw HTML. This could prove difficult to manipulate and analyze. There are three primary ways to analyze and parse this raw HTML string:

  • Use the XMLHttpRequest.responseXML property as covered in the article HTML in XMLHttpRequest .
  • Inject the content into the body of a document fragment via fragment.body.innerHTML and traverse the DOM of the fragment.
  • RegExp can be used if you always know the content of the HTML responseText beforehand. You might want to remove line breaks, if you use RegExp to scan with regard to line breaks. However, this method is a "last resort" since if the HTML code changes slightly, the method will likely fail.

Handling binary data

Although XMLHttpRequest is most commonly used to send and receive textual data, it can be used to send and receive binary content. There are several well tested methods for coercing the response of an XMLHttpRequest into sending binary data. These involve utilizing the overrideMimeType() method on the XMLHttpRequest object and is a workable solution.

However, more modern techniques are available, since the responseType attribute now supports a number of additional content types, which makes sending and receiving binary data much easier.

For example, consider this snippet, which uses the responseType of " arraybuffer " to fetch the remote content into a ArrayBuffer object, which stores the raw binary data.

For more examples check out the Sending and Receiving Binary Data page.

Monitoring progress

XMLHttpRequest provides the ability to listen to various events that can occur while the request is being processed. This includes periodic progress notifications, error notifications, and so forth.

Support for DOM progress event monitoring of XMLHttpRequest transfers follows the specification for progress events : these events implement the ProgressEvent interface. The actual events you can monitor to determine the state of an ongoing transfer are:

The amount of data that has been retrieved has changed.

The transfer is complete; all data is now in the response

Lines 3-6 add event listeners for the various events that are sent while performing a data transfer using XMLHttpRequest .

Note: You need to add the event listeners before calling open() on the request. Otherwise the progress events will not fire.

The progress event handler, specified by the updateProgress() function in this example, receives the total number of bytes to transfer as well as the number of bytes transferred so far in the event's total and loaded fields. However, if the lengthComputable field is false, the total length is not known and will be zero.

Progress events exist for both download and upload transfers. The download events are fired on the XMLHttpRequest object itself, as shown in the above sample. The upload events are fired on the XMLHttpRequest.upload object, as shown below:

Note: Progress events are not available for the file: protocol.

Progress events come in for every chunk of data received, including the last chunk in cases in which the last packet is received and the connection closed before the progress event is fired. In this case, the progress event is automatically fired when the load event occurs for that packet. This lets you now reliably monitor progress by only watching the "progress" event.

One can also detect all three load-ending conditions ( abort , load , or error ) using the loadend event:

Note there is no way to be certain, from the information received by the loadend event, as to which condition caused the operation to terminate; however, you can use this to handle tasks that need to be performed in all end-of-transfer scenarios.

Get last modified date

Do something when last modified date changes.

Let's create two functions:

And to test:

If you want to know if the current page has changed, refer to the article about document.lastModified .

Cross-site XMLHttpRequest

Modern browsers support cross-site requests by implementing the Cross-Origin Resource Sharing (CORS) standard. As long as the server is configured to allow requests from your web application's origin, XMLHttpRequest will work. Otherwise, an INVALID_ACCESS_ERR exception is thrown.

Bypassing the cache

A cross-browser compatible approach to bypassing the cache is appending a timestamp to the URL, being sure to include a "?" or "&" as appropriate. For example:

As the local cache is indexed by URL, this causes every request to be unique, thereby bypassing the cache.

You can automatically adjust URLs using the following code:

The recommended way to enable cross-site scripting is to use the Access-Control-Allow-Origin HTTP header in the response to the XMLHttpRequest.

XMLHttpRequests being stopped

If you conclude with an XMLHttpRequest receiving status=0 and statusText=null , this means the request was not allowed to be performed. It was UNSENT . A likely cause for this is when the XMLHttpRequest origin (at the creation of the XMLHttpRequest) has changed when the XMLHttpRequest is subsequently open() . This case can happen, for example, when one has an XMLHttpRequest that gets fired on an onunload event for a window, the expected XMLHttpRequest is created when the window to be closed is still there, and finally sending the request (in other words, open() ) when this window has lost its focus and another window gains focus. The most effective way to avoid this problem is to set a listener on the new window's DOMActivate event which is set once the terminated window has its unload event triggered.

Setting overrideMimeType does not work from a Worker . See Firefox bug 678057 for more details. Other browsers may handle this differently.

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • HTML in XMLHttpRequest
  • HTTP access control
  • XMLHttpRequest - REST and the Rich User Experience
  • "Using the XMLHttpRequest Object" (jibbering.com)
  • The XMLHttpRequest object: WHATWG specification
  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

Spring Boot REST XML

last modified August 2, 2023

In this article we show how to serve XML data in a Spring Boot RESTFul application. We create test methods for the RESTful controller.

Spring is a popular Java application framework for creating enterprise applications. Spring Boot is the next step in evolution of Spring framework. It helps create stand-alone, production-grade Spring based applications with minimal effort. It promotes using the convention over configuration principle over XML configurations.

RESTFul application

A RESTFul application follows the REST architectural style, which is used for designing networked applications. RESTful applications generate HTTP requests performing CRUD (Create/Read/Update/Delete) operations on resources. RESTFul applications typically return data in JSON or XML format.

Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. XML is often used in data exchange between applications.

Spring Boot REST XML example

The following application is a Spring Boot RESTful application which returns data in XML format from an H2 database using Spring Data JPA.

This is the project structure.

This is the Gradle build file. The h2 dependency includes the H2 database driver. The jackson-dataformat-xml adds Jackson XML serializer and deserializer.

The spring-boot-starter-web is a starter for building web applications with Spring MVC including RESTFul applictions. It uses Tomcat as the default embedded container.

The spring-boot-starter-data-jpa is a starter for using Spring Data JPA with Hibernate. The spring-boot-starter-test is a starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito.

In the application.yml file we write various configuration settings of a Spring Boot application. The port sets for server port and the context-path context path (application name). After these settings, we access the application at localhost:8086/rest/ . With the banner-mode property we turn off the Spring banner.

The JPA database value specifies the target database to operate on. We specify the Hibernate dialect, org.hibernate.dialect.H2Dialect in our case. The ddl-auto is the data definition language mode; the create-drop option automatically creates and drops the database schema.

The H2 database is run in memory. Also, we set the logging level for spring framework to ERROR. The application.yml file is located in the in the src/main/resources directory.

This is the City entity. Each entity must have at least two annotations defined: @Entity and @Id . Previously, we have set the ddl-auto option to create-drop which means that Hibernate will create the table schema from this entity.

The @Entity annotation specifies that the class is an entity and is mapped to a database table. The @Table annotation specifies the name of the database table to be used for mapping. With the @JacksonXmlRootElement(localName = "City") annotation we set the name for the XML output root element.

The @Id annotation specifies the primary key of an entity and the @GeneratedValue provides the strategy for generating values of primary keys. With the @JacksonXmlProperty(isAttribute = true) we set the id to be an attribute of the City element in the XML output.

With the @JacksonXmlProperty we set the name and population attributes to be the properties of City element in the XML output.

The Cities bean is a helper bean which is used to get nicer XML output.

With @JacksonXmlProperty and @JacksonXmlElementWrapper annotations we ensure that we have City elements nested in the Cities element for a an ArrayList of city objects.

The schema is automatically created by Hibernate; later, the import.sql file is executed to fill the H2 table with data.

By extending from the Spring CrudRepository , we will have some methods for our data repository implemented, including findAll and findById . This way we save a lot of boilerplate code.

ICityService provides contract methods to get all cities and get one city by its Id.

CityService contains the implementation of the findAll and findById methods. We use repository to work with data.

CityRepository is injected.

Note that the findAll method returns the Cities bean.

The findById service method calls the repositorie's findById method to get the city by its Id; if the city is not found, an empty city is returned.

This is the controller class for the Spring Boot RESTful application. The @RestController annotation creates a RESTful controller. While the traditional MVC controller uses ModelAndView , the RESTful controller simply returns the object and the object data is written directly to the HTTP response (usually) in JSON or XML format.

We inject a ICityService into the cityService field.

We map a request with the /cities path to the controller's findCities method. The default request is a GET request. By using MediaType.APPLICATION_XML_VALUE , Spring uses a message converter that produces XML data.

In the second method, we return a specific city. The URL path contains the Id of the city to be retrieved; we use the @PathVariable annotation to bind the URL template variable to the cityId parameter.

The MytControllerTest contains two methods that test the controller methods.

The Application sets up the Spring Boot application. The @SpringBootApplication enables auto-configuration and component scanning.

With ./gradlew bootRun command, we run the application. The application is deployed on embedded Tomcat server.

With the curl command, we get all cities.

Here we get one city identified by its Id.

In this article we have returned data to the client in XML format from a Spring Boot RESTful application. We used Spring Data JPA to retrieve data from H2 database.

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Spring Boot tutorials .

Spring Boot Rest XML example – Web service with XML Response

In this Spring Boot tutorial, I will show you a Restful Web service example in that Spring REST Controller can receive/consume XML Request Body and return XML Response instead of JSON. We also use Spring Data JPA to interact with database (MySQL/PostgreSQL).

More Practice: – Documentation: Spring Boot + Swagger 3 example (with OpenAPI 3) – Caching: Spring Boot Redis Cache example – Spring Boot Thymeleaf CRUD example – Spring Boot, Spring Data JPA – Building Rest CRUD API example – Spring Boot + GraphQL + MySQL example

Associations: – Spring Boot One To One example with JPA, Hibernate – Spring Boot One To Many example with JPA, Hibernate – Spring Boot Many to Many example with JPA, Hibernate

Deployment: – Deploy Spring Boot App on AWS – Elastic Beanstalk – Docker Compose: Spring Boot and MySQL example

Spring Boot XML REST Service

Return xml responses, overview of spring boot rest xml example, project structure, create & setup spring boot project, configure spring datasource, jpa, hibernate, define data model, create repository interface, configure content negotiation for xml type, create spring rest apis controller, run & test, further reading, source code.

There are two ways to render XML responses:

  • Using Jackson XML extension ( jackson-dataformat-xml ) to render XML responses is easy, just add the following dependency:
  • Using JAXB with dependency:

So XML can be rendered by annotating @XmlRootElement at the data model lass:

In this example, we’re gonna use the first way.

You can tell Controller which methods should return XML Responses by using MediaType.APPLICATION_XML_VALUE as produces value of @RequestMapping annotation.

In case you want to make all Controller methods return XML Reponses, you don’t have to mark each methods with produces=MediaType.APPLICATION_XML_VALUE . Just implement content negotiation by implementing WebMvcConfigurer and override configureContentNegotiation() .

We will build a Restful Web service that provides CRUD API for a Tutorial application in that:

  • Each Tutorial has id, title, description, published status.
  • Apis help to create, retrieve, update, delete Tutorials.
  • Apis also support custom finder methods such as find by published status or by title.
  • XML is the Content Type of HTTP Requests and Responses.

Here are the APIs:

– We make CRUD operations & finder methods with Spring Data JPA’s JpaRepository . – The database could be PostgreSQL or MySQL depending on the way we configure project dependency & datasource.

  • Spring Boot 2.2.1 (with Spring Web MVC, Spring Data JPA)
  • PostgreSQL/MySQL
  • Maven 3.6.1
  • Jackson Dataformat XML 2.10.1

spring-boot-rest-xml-example-project-structure

– WebConfig implements WebMvcConfigurer . This is where we set the default content type. – Tutorial data model class corresponds to entity and table tutorials . – TutorialRepository is an interface that extends JpaRepository for CRUD methods and custom finder methods. It will be autowired in TutorialController . – TutorialController is a RestController which has request mapping methods for RESTful requests such as: getAllTutorials , createTutorial , updateTutorial , deleteTutorial , findByPublished … – Configuration for Spring Datasource, JPA & Hibernate in application.properties . – pom.xml contains dependencies for Spring Boot, ackson Dataformat XML & MySQL/PostgreSQL.

Use Spring web tool or your development tool ( Spring Tool Suite , Eclipse, Intellij ) to create a Spring Boot project.

Then open pom.xml and add these dependencies:

We also need to add one more dependency. – If you want to use MySQL :

– or PostgreSQL :

Under src/main/resources folder, open application.properties and write these lines.

– For MySQL:

– For PostgreSQL:

  • spring.datasource.username & spring.datasource.password properties are the same as your database installation.
  • Spring Boot uses Hibernate for JPA implementation, we configure MySQL5InnoDBDialect for MySQL or PostgreSQLDialect for PostgreSQL
  • spring.jpa.hibernate.ddl-auto is used for database initialization. We set the value to update value so that a table will be created in the database automatically corresponding to defined data model. Any change to the model will also trigger an update to the table. For production, this property should be validate .

Our Data model is Tutorial with four fields: id, title, description, published. In model package, we define Tutorial class.

model/Tutorial.java

– @Entity annotation indicates that the class is a persistent Java class. – @Table annotation provides the table that maps this entity. – @Id annotation is for the primary key. – @GeneratedValue annotation is used to define generation strategy for the primary key. GenerationType.AUTO means Auto Increment field. – @Column annotation is used to define the column in database that maps annotated field.

Let’s create a repository to interact with Tutorials from the database. In repository package, create TutorialRepository interface that extends JpaRepository .

repository/TutorialRepository.java

Now we can use JpaRepository’s methods: save() , findOne() , findById() , findAll() , count() , delete() , deleteById() … without implementing these methods.

We also define custom finder methods: – findByPublished() : returns all Tutorials with published having value as input published . – findByTitleContaining() : returns all Tutorials which title contains input title .

The implementation is plugged in by Spring Data JPA automatically.

More Derived queries at: JPA Repository query example in Spring Boot

Custom query with @Query annotation: Spring JPA @Query example: Custom query in Spring Boot

You can modify this Repository: – to work with Pagination, the instruction can be found at: Spring Boot Pagination & Filter example | Spring JPA, Pageable – or to sort/order by multiple fields with the tutorial: Spring Data JPA Sort/Order by multiple Columns | Spring Boot

You also find way to write Unit Test for this JPA Repository at: Spring Boot Unit Test for JPA Repository with @DataJpaTest

Now we’re gonna implement content negotiation in our Spring Boot project.

config/WebConfig.java

Finally, we create a controller that provides APIs for creating, retrieving, updating, deleting and finding Tutorials.

controller/TutorialController.java

– @CrossOrigin is for configuring allowed origins. – @RestController annotation is used to define a controller and to indicate that the return value of the methods should be be bound to the web response body. – @RequestMapping("/api") declares that all Apis’ url in the controller will start with /api . – We use @Autowired to inject TutorialRepository bean to local variable.

Run Spring Boot application with command: mvn spring-boot:run .

tutorials table will be automatically generated in Database. If you check MySQL for example, you can see things like this:

Create Tutorials:

spring-boot-rest-xml-example-crud-api-create-item

Get all Tutorials:

spring-boot-rest-xml-example-crud-api-retrieve-all-items

Get a Tutorial by Id:

spring-boot-rest-xml-example-crud-api-retrieve-item

Update some Tutorials:

spring-boot-rest-xml-example-crud-api-update-item

Find all published Tutorials:

spring-boot-rest-xml-example-crud-api-find-items-published

Find all Tutorials which title contains ‘zkoder’:

spring-boot-rest-xml-example-crud-api-find-items-by-title

Delete a Tutorial:

spring-boot-rest-xml-example-crud-api-delete-item

Delete all Tutorials with API: DELETE http://localhost:8080/api/tutorials/

Today we’ve built a Spring Boot Rest XML example using Jackson XML extension to render XML and Spring Data JPA to interact with MySQL/PostgreSQL. You’ve known way to consume XML in Request Body and return XML Response.

If you want to learn more about Spring Boot Webservice that work with JSON data in Requests and Responses, please visit: Spring Boot, Spring Data JPA – Building Rest CRUD API example

Or Documentation: Spring Boot + Swagger 3 example (with OpenAPI 3)

Happy learning! See you again.

  • https://github.com/FasterXML/jackson-dataformat-xml
  • Secure Spring Boot App with Spring Security & JWT Authentication
  • Spring Data JPA Reference Documentation

You can find the complete source code for this tutorial on Github .

3 thoughts to “Spring Boot Rest XML example – Web service with XML Response”

very good, how do a client ???

Thanks for complete tutorial and working code.

I ᴡant to to thank you for this good tutorial!!

Comments are closed to reduce spam. If you have any question, please send me an email.

Buy me a coffee

  • Json Formatter

Tableau

Tableau REST API Help

Rest api example requests.

This topic illustrates the structure of REST API requests by showing the raw HTTP, including both headers and the body (as appropriate).

How to read the examples

In this topic, the first line of each example shows the verb (GET, POST, etc.) and the portion of the URI that describes the resource and the REST API version number. For example, for signing in the example URI shows this:

This indicates that you should make a POST request, using version 2.2 of the REST API, and that the URI should be something like the following:

where my-server is the name or IP address of the computer where Tableau Server is installed.

The lines that follow the verb and endpoint show the headers that you must include.

If the examples shows a POST or PUT request, there's a blank line, followed by the XML information that's included in the body.

The first REST API request in a session must be a sign-in request. This is a POST request that sends the user credentials in the body of the request. Because this is a POST request, the request must include the Content-Type header. You can send your the body of the request block as XML or JSON. For example, the following shows how you send an XML request block.

You can also send the request using JSON by setting the Content-Type to application/json . You can receive the response in JSON or XML by setting the Accept header to application/json or application/xml .

Get a list of resources

To get a list of resources like users, you send a GET request. The request must include an X-Tableau-Auth header with the authentication token that was returned in the Sign In call. There is no request body.

The following examples shows a request that gets a list of users.

Create a new resource

To create a new resource, such as a new user, you send a POST request. The request must include:

An X-Tableau-Auth header with the authentication token that was returned in the Sign In call

A Content-Type header set to text/xml or application/xml if you are sending an XML block, or set to application/json for a JSON request block.

A request body with an XML or a JSON block that includes the information for the new resource. The XML and JSON block is defined by an XML schema . The information in the request block depends on what type of resource you're creating.

The following example shows a request that creates a new user in an XML request. The response returns the ID of the resource you created.

This example shows the same request in JSON.

Update a resource

To update an existing resource, you send a PUT request and include the ID of the resource that was returned in POST request. The request must include:

An X-Tableau-Auth header with the authentication token that was returned in the Sign In call.

A Content-Type header set to text/xml .

A request body with an XML or JSON block that includes the changes for the existing resource. The XML or JSON block is defined by an XML schema . The information in the request block depends on the type of resource that you're updating.

The following example shows a request that updates an existing user. The URI includes the ID of the user that was returned from the POST request.

Delete a resource

To remove resource, you send a DELETE request. The request must include an X-Tableau-Auth header with the authentication token that was returned in the Sign In call. There is no request body.

The following example shows a request that deletes an existing user.

Publish a resource

To publish a resource such as a data source or a workbook, you have two options. You can publish the resource using a single call. In that case, you create a POST request with the content type of multipart/mixed , and you include the resource in the body of the request.

Another option is to publish the resource in pieces. For that scenario, you initiate a file upload as a POST request, and then send a series of POST requests that each append another piece of the resource. When the resource has been completely uploaded, you make a final POST request to finish the upload.

For details about how to publish, see Publishing Resources .

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Return XML Response in REST Service

I am writing a RESTful web service where in I want to return a XML containing some resultset. I have used XSTREAM and parsed the object into XML string. Since I need to return this string, I need to know how to pass it back to the calling client.

One way is to return the RESPONSE to the calling client. And my sample code here shows what it is that I am trying to do.

Unfortunately it doesn't return the entity, though the status code is 200. Am I instantiating the ResponseBuilder incorrectly? I also saw somewhere that it should be instantiated as follows:

Please suggest what is the apt way to return XML in response.

I AM USING APACHE CXF for RESTFUL SERVICES. (Version 2.2.3 -- i guess) :D Thanks in Advance for all the help.

bluish's user avatar

2 Answers 2

It was just a cleaning problem. It eventually worked. I created the response in following way eventually.

It works just fine. I hope it helps someone.

  • What is the value 'xmlString'? And how is it define? –  NayMak Feb 26, 2020 at 15:03

Does the HTTP Response have the correct content-type header to identify that it is Xml i.e. text/xml or application\xml ? Checkout The Proper Content Type for XML Feeds .

The response status 200 is just one of the standard HTTP Response Codes that means the request has succeeded so only return it if that is the case.

Dave Anderson's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct .

Not the answer you're looking for? Browse other questions tagged java rest cxfrs or ask your own question .

  • The Overflow Blog
  • Journey to the cloud part I: Migrating Stack Overflow Teams to Azure
  • Featured on Meta
  • Our Design Vision for Stack Overflow and the Stack Exchange network
  • Temporary policy: Generative AI (e.g., ChatGPT) is banned
  • Call for volunteer reviewers for an updated search experience: OverflowAI Search
  • Discussions experiment launching on NLP Collective

Hot Network Questions

  • Could a planet orbiting a star have a habitable moon and this moon have its own moon orbiting it?
  • Risky Surgery and resistance to slashing damage
  • How to put a tube in a used tubeless tire
  • Are there any good alternatives to firearms for 1920s aircrafts?
  • Idiom for frustrating someone else's plans by taking what the other person wanted in the first place
  • Does political lobbying exist in North Korea?
  • Calculating integral with exponential function and parameter
  • Why is there nearly no 1x road bikes?
  • Question about number format for numbers between zero and one
  • CAT: Cat Approved TUIs
  • Is there any way I can recycle a device that has been iCloud locked?
  • Sci-fi story involving telescopic technology that could reach out into space and view the universe from remote locations
  • Why can we take the collection of all open balls?
  • Why people buy high dividend stock?
  • Why are hangars so high?
  • What is a complete understanding?
  • Would it harm game balance to allow potions to be self-administered with a bonus action?
  • What program in Linux computes the hash of the input password when you log in?
  • File Organiser in Python
  • Male and female seahorses: which is which
  • Is the existence of substructures satisfying a theory absolute?
  • How can I use Windows .bat files to create folder above current folder?
  • Golf the fast growing hierarchy
  • Why can't I move my knight from d5 to c7?

rest with xml example

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot
  • Write an Interview Experience
  • Share Your Campus Experience
  • Spring Tutorial

Basics of Spring Framework

  • Introduction to Spring Framework
  • Spring Framework Architecture
  • 10 Reasons to Use Spring Framework in Projects
  • Spring Initializr
  • Difference Between Spring DAO vs Spring ORM vs Spring JDBC
  • Top 10 Most Common Spring Framework Mistakes
  • Spring vs. Struts in Java

Software Setup and Configuration

  • How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
  • How to Create and Setup Spring Boot Project in Spring Tool Suite?
  • How to Create a Spring Boot Project with IntelliJ IDEA?
  • How to Create and Setup Spring Boot Project in Eclipse IDE?
  • How to Create a Dynamic Web Project in Eclipse/Spring Tool Suite?
  • How to Run Your First Spring Boot Application in IntelliJ IDEA?
  • How to Run Your First Spring Boot Application in Spring Tool Suite?
  • How to Turn on Code Suggestion in Eclipse or Spring Tool Suite?

Core Spring

  • Spring – Understanding Inversion of Control with Example
  • Spring – BeanFactory
  • Spring – ApplicationContext
  • Spring – Difference Between BeanFactory and ApplicationContext
  • Spring Dependency Injection with Example
  • Spring – Difference Between Inversion of Control and Dependency Injection
  • Spring – Injecting Objects By Constructor Injection
  • Spring – Setter Injection with Map
  • Spring – Dependency Injection with Factory Method
  • Spring – Dependency Injection by Setter Method
  • Spring – Setter Injection with Non-String Map
  • Spring – Constructor Injection with Non-String Map
  • Spring – Constructor Injection with Map
  • Spring – Setter Injection with Dependent Object
  • Spring – Constructor Injection with Dependent Object
  • Spring – Setter Injection with Collection
  • Spring – Setter Injection with Non-String Collection
  • Spring – Constructor Injection with Collection
  • Spring – Injecting Objects by Setter Injection
  • Spring – Injecting Literal Values By Setter Injection
  • Spring – Injecting Literal Values By Constructor Injection
  • Bean life cycle in Java Spring
  • Custom Bean Scope in Spring
  • How to Create a Spring Bean in 3 Different Ways?
  • Spring – IoC Container
  • Spring – Autowiring
  • Singleton and Prototype Bean Scopes in Java Spring
  • How to Configure Dispatcher Servlet in web.xml File?
  • Spring – Configure Dispatcher Servlet in Three Different Ways
  • How to Configure Dispatcher Servlet in Just Two Lines of Code in Spring?
  • Spring – When to Use Factory Design Pattern Instead of Dependency Injection
  • How to Create a Simple Spring Application?
  • Spring – init() and destroy() Methods with Example
  • Spring WebApplicationInitializer with Example
  • Spring – Project Modules
  • Spring – Remoting by HTTP Invoker
  • Spring – Expression Language(SpEL)
  • Spring – Variable in SpEL
  • What is Ambiguous Mapping in Spring?
  • Spring – Add New Query Parameters in GET Call Through Configurations
  • Spring – Integrate HornetQ
  • Remoting in Spring Framework
  • Spring – Application Events
  • Spring c-namespace with Example
  • Parse Nested User-Defined Functions using Spring Expression Language (SpEL)
  • Spring – AbstractRoutingDataSource
  • Circular Dependencies in Spring
  • Spring – ResourceLoaderAware with Example
  • Spring Framework Standalone Collections
  • How to Create a Project using Spring and Struts 2?
  • Spring – Perform Update Operation in CRUD
  • How to Transfer Data in Spring using DTO?
  • Spring – Resource Bundle Message Source (i18n)
  • Spring Application Without Any .xml Configuration
  • Spring – BeanPostProcessor
  • Spring and JAXB Integration
  • Spring – Difference Between Dependency Injection and Factory Pattern
  • Spring – REST Pagination
  • Spring – Remoting By Burlap
  • Spring – Remoting By Hessian
  • Spring with Castor Example

Spring – REST XML Response

  • Spring – Inheriting Bean
  • Spring – Change DispatcherServlet Context Configuration File Name
  • Spring – JMS Integration
  • Spring – Difference Between RowMapper and ResultSetExtractor
  • Spring with Xstream
  • Spring – RowMapper Interface with Example
  • Spring – util:constant
  • Spring – Static Factory Method
  • Spring – FactoryBean
  • Difference between EJB and Spring
  • Spring Framework Annotations
  • Spring Core Annotations
  • Spring – Stereotype Annotations
  • Spring @Bean Annotation with Example
  • Spring @Controller Annotation with Example
  • Spring @Value Annotation with Example
  • Spring @Configuration Annotation with Example
  • Spring @ComponentScan Annotation with Example
  • Spring @Qualifier Annotation with Example
  • Spring @Service Annotation with Example
  • Spring @Repository Annotation with Example
  • Spring – Required Annotation
  • Spring @Component Annotation with Example
  • Spring @Autowired Annotation
  • Spring – @PostConstruct and @PreDestroy Annotation with Example
  • Java Spring – Using @PropertySource Annotation and Resource Interface
  • Java Spring – Using @Scope Annotation to Set a POJO’s Scope
  • Spring @Required Annotation with Example
  • Spring Boot Tutorial
  • Spring MVC Tutorial

Spring with REST API

  • Spring – REST JSON Response
  • Spring – REST Controller

Spring Data

  • What is Spring Data JPA?
  • Spring Data JPA – Find Records From MySQL
  • Spring Data JPA – Delete Records From MySQL
  • Spring Data JPA – @Table Annotation
  • Spring Data JPA – Insert Data in MySQL Table
  • Spring Data JPA – Attributes of @Column Annotation with Example
  • Spring Data JPA – @Column Annotation
  • Spring Data JPA – @Id Annotation
  • Introduction to the Spring Data Framework
  • Spring Boot | How to access database using Spring Data JPA
  • How to Make a Project Using Spring Boot, MySQL, Spring Data JPA, and Maven?

Spring JDBC

  • Spring – JDBC Template
  • Spring JDBC Example
  • Spring – SimpleJDBCTemplate with Example
  • Spring – Prepared Statement JDBC Template
  • Spring – NamedParameterJdbcTemplate
  • Spring – Using SQL Scripts with Spring JDBC + JPA + HSQLDB
  • Spring – ResultSetExtractor

Spring Hibernate

  • Spring Hibernate Configuration and Create a Table in Database
  • Hibernate Lifecycle
  • Java – JPA vs Hibernate
  • Spring ORM Example using Hibernate
  • Hibernate – One-to-One Mapping
  • Hibernate – Cache Eviction with Example
  • Hibernate – Cache Expiration
  • Hibernate – Enable and Implement First and Second Level Cache
  • Hibernate – Save Image and Other Types of Values to Database
  • Hibernate – Pagination
  • Hibernate – Different Cascade Types
  • Hibernate Native SQL Query with Example
  • Hibernate – Caching
  • Hibernate – @Embeddable and @Embedded Annotation
  • Hibernate – Eager/Lazy Loading
  • Hibernate – get() and load() Method
  • Hibernate Validator with Example
  • CRUD Operations using Hibernate
  • Hibernate Example without IDE
  • Hibernate – Inheritance Mapping
  • Automatic Table Creation Using Hibernate
  • Hibernate – Batch Processing
  • Hibernate – Component Mapping
  • Hibernate – Mapping List
  • Hibernate – Collection Mapping
  • Hibernate – Bag Mapping
  • Hibernate – Difference Between List and Bag Mapping
  • Hibernate – SortedSet Mapping
  • Hibernate – SortedMap Mapping
  • Hibernate – Native SQL
  • Hibernate – Logging by Log4j using xml File
  • Hibernate – Many-to-One Mapping
  • Hibernate – Logging By Log4j Using Properties File
  • Hibernate – Table Per Concrete Class Using Annotation
  • Hibernate – Table Per Subclass using Annotation
  • Hibernate – Interceptors
  • Hibernate – Many-to-Many Mapping
  • Hibernate – Types of Mapping
  • Hibernate – Criteria Queries
  • Hibernate – Table Per Hierarchy using Annotation
  • Hibernate – Table Per Subclass Example using XML File
  • Hibernate – Table Per Hierarchy using XML File
  • Hibernate – Create POJO Classes
  • Hibernate – Web Application
  • Hibernate – Table Per Concrete Class using XML File
  • Hibernate – Generator Classes
  • Hibernate – SQL Dialects
  • Hibernate – Query Language
  • Hibernate – Difference Between ORM and JDBC
  • Hibernate – Annotations
  • Hibernate Example using XML in Eclipse
  • Hibernate – Create Hibernate Configuration File with the Help of Plugin
  • Hibernate Example using JPA and MySQL
  • Hibernate – One-to-Many Mapping
  • Aspect Oriented Programming and AOP in Spring Framework
  • Spring – AOP Example (Spring1.2 Old Style AOP)
  • Spring – AOP AspectJ Xml Configuration
  • Spring AOP – AspectJ Annotation
  • Usage of @Before, @After, @Around, @AfterReturning, and @AfterThrowing in a Single Spring AOP Project

Spring Security

  • Introduction to Spring Security and its Features
  • Some Important Terms in Spring Security
  • OAuth2 Authentication with Spring and Github
  • Spring Security at Method Level
  • Spring – Security JSP Tag Library
  • Spring – Security Form-Based Authentication
  • Spring Security – Remember Me
  • Spring Security XML
  • Spring Security Project Example using Java Configuration
  • How to Change Default User and Password in Spring Security?
  • Spring – Add Roles in Spring Security
  • Spring – Add User Name and Password in Spring Security

The popularity of REST API is increasing day by day as it fulfills architecting an application in a convenient manner. A REST API is an acronym for ‘Representational state transfer’. It is also called RESTful web services. It is also a ‘Controller’, but with a difference that Rest Controller returns Data, while Controller returns a View of ‘Model-View-Controller’ architecture. REST API can work on all HTTP methods like ( GET, POST, PUT, PATCH, DELETE, etc ). These methods correspond to create, read, update, and delete ( CRUD ) operations, respectively. It can return many types of data. JSON is considered the standard form for data transferring between web applications. 

Data types that REST API can return are as follows: 

  • JSON (JavaScript Object Notation)
Pre-requisite: Though JSON is the standard form to transfer data among applications, it comes with some disadvantages which are overcome in XML format data transferring.

The advantages of XML are as follows: 

  • It is an Extensible markup language that uses tags for data definition.
  • It supports namespaces.
  • It supports comments.
  • It supports various encoding.
  • Last but not the least, XML is more secure than JSON.

Note : 

  • JSON is less secure because of the absence of a JSON parser in the browser.
  • JSONP is dangerous because it allows cross-origin exchanges of data.

REST API – XML Response

  • When we create a Spring Boot project with ‘Starter Web’ dependency, we only get support for returning data in JSON format, with the help of the Jackson library.
  • To embed support for returning data in XML format we need third-party dependencies.
  • There are many libraries that support XML return format, for Example – Jackson, JAXB, etc.

Working of Rest XML Response

Project Structure – Maven

Way 1: Using Jackson 

The Jackson library is already present in the Spring framework’s classpath for our application. We just need to add an extension to the Jackson library that can work with XML data responses. To add the extension, add the following dependency in the project build.

Maven – pom.xml

After adding the above dependency and updating the project, the Jackson XML extension will get added in the classpath so the Spring MVC will automatically pick this up for XML responses.

A. File: pom.xml (Project configuration)

B. Bootstrapping of application

Example: GfgRestXmlResponseApplication.java

  C. Object to be return as XML response (EntityModel.java)

This class acts as a User object ( bean ) whose fields will be mapped to XML tags respectively. It also requires Getter/Setter methods which are automatically generated using ‘@Data’ annotation of the ‘Lombok’ library. To embed the Lombok library in the project, add the following dependency in the project build.

D. REST API returning XML response (RestXMLResponseController.java)

This REST API controller is configured to return data specifically in XML format, using produces attribute of @RequestMapping annotation.

XML Response returned by get() method

XML Response returned by getById() method

E. ConsumeXMLResponse.java (Get the REST API response)

  • The data returned in XML format by REST API needs to be consumed and make to use.
  • Spring Framework provides a convenient way to consume REST responses with the help of Spring’s ‘RestTemplate’.
  • It benefits us by preventing the need to write boilerplate code.
  • RestTemplate provides us with methods that are HTTP methods specific.
  • Here for GET HTTP request, the ‘getForEntity()’ method is used that accepts URL to @GetMapping method, a class to which response will be mapped to and additional object parameters to URL.
  • This method will return a ResponseEntity<> object.

F. File: OutputController.java (Regular controller)

This MVC Controller uses the above class to get the XML response returned by REST API. Also, after getting the data it returns us a modified view ( View.html)

G. File: View.html (Display the XML response)

REST XML Response in HTML

Way 2: Using JAXB

To use the JAXB library, add the following dependency in the project built.

File: Maven – pom.xml

To make it work you have to use @XmlRootElement annotation of the same library on an object which will be mapped to XML response.

Example: EntityModel.java

Note : You can also use Jersey dependency for developing RESTful APIs. The main advantage of using it is that it already has a JAX-RS library which eventually uses JAXB libraries.

Please Login to comment...

Improve your coding skills with practice.

REST API Tutorial – REST Client, REST Service, and API Calls Explained With Code Examples

Ever wondered how login/signup on a website works on the back-end? Or how when you search for "cute kitties" on YouTube, you get a bunch of results and are able to stream off of a remote machine?

In this beginner friendly guide, I will walk you through the process of setting up a RESTful API. We'll declassify some of the jargon and have a look at how we can code a server in NodeJS. Let's dive a bit deeper into JavaScript!

Get that jargon away

So, what is REST? According to Wikipedia:

Representational state transfer ( REST ) is a software architectural style that defines a set of constraints to be used for creating Web services. RESTful Web services allow the requesting systems to access and manipulate textual representations of Web resources by using a uniform and predefined set of stateless operations

Let's demystify what that means (hopefully you got the full form). REST is basically a set of rules for communication between a client and server. There are a few constraints on the definition of REST:

  • Client-Server Architecture : the user interface of the website/app should be separated from the data request/storage, so each part can be scaled individually.
  • Statelessness : the communication should have no client context stored on server. This means each request to the server should be made with all the required data and no assumptions should be made if the server has any data from previous requests.
  • Layered system : client should not be able to tell if it is communicating directly with the server or some intermediary. These intermediary servers (be it proxy or load balancers) allow for scalability and security of the underlying server.

Okay, so now that you know what RESTful services are, here are some of the terms used in the heading:

  • REST Client : code or an app that can access these REST services. You are using one right now! Yes, the browser can act as an uncontrolled REST client (the website handles the browser requests). The browser, for a long time, used an in-built function called XMLHttpRequest for all REST requests. But, this was succeeded by FetchAPI , a modern, promise based approach to requests. Others examples are code libraries like axios , superagent and got or some dedicated apps like Postman (or an online version, postwoman !), or a command line tool like cURL !.
  • REST Service : the server. There are many popular libraries that make creation of these servers a breeze, like ExpressJS for NodeJS and Django for Python.
  • REST API : this defines the endpoint and methods allowed to access/submit data to the server. We will talk about this in great detail below. Other alternatives to this are: GraphQL, JSON-Pure and oData.

So tell me now, how does REST look?

In very broad terms, you ask the server for a certain data or ask it to save some data, and the server responds to the requests.

In programming terms, there is an endpoint (a URL) that the server is waiting to get a request. We connect to that endpoint and send in some data about us (remember, REST is stateless, no data about the request is stored) and the server responds with the correct response.

Words are boring, let me give you a demonstration. I will be using Postman to show you the request and response:

image-162

The returned data is in JSON (JavaScript Object Notation) and can be accessed directly.

Here, https://official-joke-api.appspot.com/random_joke is called an endpoint of an API. There will be a server listening on that endpoint for requests like the one we made.

Anatomy of REST:

Alright, so now we know that data can be requested by the client and the server will respond appropriately. Let's look deeper into how a request is formed.

  • Endpoint : I have already told you about this. For a refresher, it is the URL where the REST Server is listening.
  • Method : Earlier, I wrote that you can either request data or modify it, but how will the server know what kind of operation the client wants to perform? REST implements multiple 'methods' for different types of request, the following are most popular: - GET : Get resource from the server. - POST : Create resource to the server. - PATCH or PUT : Update existing resource on the server. - DELETE : Delete existing resource from the server.
  • Headers : The additional details provided for communication between client and server (remember, REST is stateless). Some of the common headers are: Request: - host : the IP of client (or from where request originated) - accept-language : language understandable by the client - user-agent : data about client, operating system and vendor Response : - status : the status of request or HTTP code. - content-type : type of resource sent by server. - set-cookie : sets cookies by server
  • Data : (also called body or message) contains info you want to send to the server.

Enough with the details – show me the code.

Let's begin coding a REST Service in Node. We will be implementing all the things we learnt above. We will also be using ES6+ to write our service in.

Make sure you have Node.JS installed and node and npm are available in your path. I will be using Node 12.16.2 and NPM 6.14.4.

Create a directory rest-service-node and cd into it:

Initialize the node project:

The -y flag skips all the questions. If you want to fill in the whole questionnaire, just run npm init .

Let's install some packages. We will be using the ExpressJS framework for developing the REST Server. Run the following command to install it:

What's body-parser there for? Express, by default, is incapable of handling data sent via POST request as JSON. body-parser allows Express to overcome this.

Create a file called server.js and add the following code:

The first two lines are importing Express and body-parser.

Third line initializes the Express server and sets it to a variable called app .

The line, app.use(bodyParser.json()); initializes the body-parser plugin.

Finally, we are setting our server to listen on port 5000 for requests.

Getting data from the REST Server:

To get data from a server, we need a GET request. Add the following code before app.listen :

We have created a function sayHi which takes two parameters req and res (I will explain later) and sends a 'Hi!' as response.

app.get() takes two parameters, the route path and function to call when the path is requested by the client. So, the last line translates to: Hey server, listen for requests on the '/' (think homepage) and call the sayHi function if a request is made.

app.get also gives us a request object containing all the data sent by the client and a response object which contains all the methods with which we can respond to the client. Though these are accessible as function parameters, the general naming convention suggests we name them res for response and req for request .

Enough chatter. Let's fire up the server! Run the following server:

If everything is successful, you should see a message on console saying: Server is running on port 5000.

Note: You can change the port to whatever number you want.

image-160

Open up your browser and navigate to http://localhost:5000/ and you should see something like this:

image-161

There you go! Your first GET request was successful!

Sending data to REST Server:

As we have discussed earlier, let's setup how we can implement a POST request into our server. We will be sending in two numbers and the server will return the sum of the numbers. Add this new method below the app.get :

Here, we will be sending the data in JSON format, like this:

Let's get over the code:

On line 1, we are invoking the . post() method of ExpressJS, which allows the server to listen for POST requests. This function takes in the same parameters as the .get() method. The route that we are passing is /add , so one can access the endpoint as http://your-ip-address:port/add or in our case localhost:5000/add . We are inlining our function instead of writing a function elsewhere.

On line 2, we have used a bit of ES6 syntax, namely, object destructuring. Whatever data we send via the request gets stored and is available in the body of the req object. So essentially, we could've replaced line 2 with something like:

On line 3, we are using the send() function of the res object to send the result of the sum. Again, we are using template literals from ES6. Now to test it (using Postman):

image-163

So we have sent the data 5 and 10 as a and b using them as the body. Postman attaches this data to the request and sends it. When the server receives the request, it can parse the data from req.body , as we did in the code above. The result is shown below.

Alright, the final code:

REST Client:

Okay, we have created a server, but how do we access it from our website or webapp? Here the REST client libraries will come in handy.

We will be building a webpage which will contain a form, where you can enter two numbers and we will display the result. Let's start.

First, let's change the server.js a bit:

We imported a new package path , which is provided by Node, to manipulate path cross-platform. Next we changed the GET request on '/' and use another function available in res , ie. sendFile , which allows us to send any type of file as response. So, whenever a person tries to navigate to '/', they will get our index.html page.

Finally, we changed our app.post function to return the sum as JSON and convert both a and b to integers.

Let's create an html page, I will call it index.html , with some basic styling:

Let's add a script tag just before the closing body tag, so we don't need to maintain a .js file. We will begin by listening for the submit event and call a function accordingly:

First we need to prevent page refresh when the 'Add' button is clicked. This can be done using the preventDefault() function. Then, we will get the value of the inputs at that instant:

Now we will make the call to the server with both these values a and b . We will be using the Fetch API , built-in to every browser for this.

Fetch takes in two inputs, the URL endpoint and a JSON request object and returns a Promise . Explaining them here will be out-of-bounds here, so I'll leave that for you.

Continue inside the sendData() function:

First we are passing the relative URL of the endpoint as the first parameter to fetch . Next, we are passing an object which contains the method we want Fetch to use for the request, which is POST in this case.

We are also passing headers , which will provide information about the type of data we are sending ( content-type ) and the type of data we accept as response ( accept ).

Next we pass body . Remember we typed the data as JSON while using Postman? We're doing kind of a similar thing here. Since express deals with string as input and processes it according to content-type provided, we need to convert our JSON payload into string. We do that with JSON.stringify() . We're being a little extra cautious and parsing the input into integers, so it doesn't mess up our server (since we haven't implemented any data-type checking).

Finally, if the promise (returned by fetch) resolves, we will get that response and convert it into JSON. After that, we will get the result from the data key returned by the response. Then we are simply displaying the result on the screen.

At the end, if the promise is rejected, we will display the error message on the console.

Here's the final code for index.html :

I have spun up a little app on glitch for you to test.

Conclusion:

So in this post, we learnt about REST architecture and the anatomy of REST requests. We worked our way through by creating a simple REST Server that serves GET and POST requests and built a simple webpage that uses a REST Client to display the sum of two numbers.

You can extend this for the remaining types of requests and even implement a full featured back-end CRUD app .

I hope you have learned something from this. If you have any questions, feel free to reach out to me over twitter! Happy Coding!

Read more posts .

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

XML Tutorial

Xpath tutorial, xslt tutorial, xquery tutorial, xsd data types, web services, xml examples, viewing xml files.

View a simple XML file (note.xml) View the same XML file with an error View an XML CD catalog View an XML plant catalog View an XML food menu

Examples explained

XML and CSS

View an XML CD catalog View the corresponding CSS file Display the CD catalog formatted with the CSS file

XML and XSLT

View an XML food menu Display the food menu styled with an XSLT style sheet

Parsing XML and the XML DOM

View a simple XML file (note.xml) Parse an XML string Parse the XML file

XML Output From a Server

See how ASP can return XML See how PHP can return XML View XML output from a database

Create your site with Spaces

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials

Top references, top examples, get certified.

rest with xml example

Read the Gartner Magic Quadrant report

Gartner names MuleSoft a Leader

Unleash the power of Salesforce Customer 360 through integration

Unleash the power of Salesforce Customer 360 through integration

Anypoint Platform Fundamentals

Anypoint Platform Fundamentals

Event MuleSoft CONNECT

MuleSoft at World Tour

© Copyright 2023 Salesforce, Inc. All rights reserved .

HowTo – Build a REST API with XML payload

rest with xml example

There is hardly any argument on the fact that APIs are increasingly becoming an important part of how companies do business. API has become the de facto standard to unlock one of their most valuable resources, data.

Pre-requisites:

  • Sign up for an Anypoint Platform Account .
  • Download Anypoint Platform Design Tool –  MuleSoft  Anypoint Studio . In this post, we are using version 5.4 of Anypoint Studio with the new “Studio Light Theme”. You can always revert to the old theme in Preferences.
  • A database where we can create and load a sample table required for this project. In this example, we will use an instance of the  MySQL database .
  • To follow the example in this guide, run the SQL script customer.sql to set up the table and load it with some sample data.

Fullscreen_12_25_15__4_17_PM

Related articles

real-sftp

Setting up real-time Secure File Transfer Protocol (SFTP) data integration with webhooks

  • Saggi Neumann
  • 11 mins read

rest with xml example

Everything you need to know to migrate from Mule 3 to Mule 4 from Air Canada

  • Jay Kizhakkevalappil
  • 21 mins read

Automate-jenkins-pipeline

How to automate the Jenkins release pipelines

  • Peter Dunworth
  • 9 mins read

Get the latest news delivered to your inbox

Subscribe and get notified each time a new episode is published

You have been redirected.

You have been redirected to this page because Servicetrace has been acquired by MuleSoft. Click here to learn more.

IMAGES

  1. Spring Boot Rest XML example

    rest with xml example

  2. Spring Restful web services xml example

    rest with xml example

  3. Working with REST Requests

    rest with xml example

  4. Spring Boot Rest XML example

    rest with xml example

  5. Spring Boot Rest XML example

    rest with xml example

  6. Spring Boot Rest XML example

    rest with xml example

VIDEO

  1. PRESET AM🌴 PRESET XML🎟 SOUND🎶 OW OW ADE SU NIKAH REMIX PAPA ADUNG

  2. Present XMl in comment

  3. Spring MVC Tutorials 38 Web Services 08 Supporting XML format for REST APIs

  4. Lec:-10 || XML ATTRIBUTES & XML COMMENTS || #nic #xml

  5. lec1 part4 (XML example,XML syntax)

  6. Hikvision Password Reset Using SADP Tool via XML/QR Code

COMMENTS

  1. Build a REST API with XML Payload

    In this post, we will go step by step through an example to build out a RESTful web service with XML request and response payload. Check out the complete project on Anypoint Exchange. What's...

  2. Spring REST XML and JSON Example

    Welcome to Spring Restful Web Services XML and JSON example. Sometime back I wrote an article about Spring REST JSON and I got a lot of comments asking how to change the program to support XML. I got some emails also asking how to make application supports both XML as well as JSON. Spring REST XML and JSON

  3. Using XMLHttpRequest

    Using XMLHttpRequest. In this guide, we'll take a look at how to use XMLHttpRequest to issue HTTP requests in order to exchange data between the website and a server. Examples of both common and more obscure use cases for XMLHttpRequest are included. To send an HTTP request, create an XMLHttpRequest object, open a URL, and send the request.

  4. Spring Boot REST XML

    Spring Boot REST XML example The following application is a Spring Boot RESTful application which returns data in XML format from an H2 database using Spring Data JPA.

  5. Spring Boot Rest XML example

    In this Spring Boot tutorial, I will show you a Restful Web service example in that Spring REST Controller can receive/consume XML Request Body and return XML Response instead of JSON. We also use Spring Data JPA to interact with database (MySQL/PostgreSQL). More Practice: - Documentation: Spring Boot + Swagger 3 example (with OpenAPI 3)

  6. REST API Best Practices

    REST API Design Best Practices. 1. Use JSON as the Format for Sending and Receiving Data. In the past, accepting and responding to API requests were done mostly in XML and even HTML. But these days, JSON (JavaScript Object Notation) has largely become the de-facto format for sending and receiving API data.

  7. What Is a REST API? Examples, Uses & Challenges

    The Postman Team June 28, 2023 · 11 mins Originally published on July 9, 2020 Application programming interfaces ( APIs ) come in many shapes and sizes, which can make it pretty difficult for newcomers to understand what they are and how they can be used. At Postman we enjoy working with APIs. Seriously. We do.

  8. Sending XML Request with REST-assured

    1.2. Sending Request with REST-assured. Sending the XML request body is very simple. We need to set the content type to "application/xml" (or any other custom mediatype, if any) and then pass the XML string to the given ().body (xml) method. A complete example of sending the XML request to a POST API is: 2.

  9. Getting Started

    H2. Change the Name to "Payroll" and then choose "Generate Project". A .zip will download. Unzip it. Inside you'll find a simple, Maven-based project including a pom.xml build file (NOTE: You can use Gradle. The examples in this tutorial will be Maven-based.) Spring Boot can work with any IDE.

  10. REST API Example Requests

    A request body with an XML or a JSON block that includes the information for the new resource. The XML and JSON block is defined by an XML schema. The information in the request block depends on what type of resource you're creating. The following example shows a request that creates a new user in an XML request.

  11. java

    I am writing a RESTful web service where in I want to return a XML containing some resultset. I have used XSTREAM and parsed the object into XML string. Since I need to return this string, I need to know how to pass it back to the calling client. One way is to return the RESPONSE to the calling client.

  12. REST API: Your Guide to Getting Started Quickly

    While REST doesn't define data formats, it's usually associated with exchanging JSON or XML documents between a client and a server. We're going to use a simple service and a web browser to learn about the fundamentals of REST. REST Setup. For this tutorial, you'll need a system with Docker installed.

  13. Produce XML Response with Spring WebMVC Controller

    In this Spring REST XML example, I am writing hello world example for REST APIs using Spring REST features. In this example, I will be creating two APIs which will return XML representation of resources. Download Sourcecode 1. Maven Dependencies Let's start with runtime dependencies which you will need to write these REST APIs.

  14. Spring

    The popularity of REST API is increasing day by day as it fulfills architecting an application in a convenient manner. A REST API is an acronym for 'Representational state transfer'. It is also called RESTful web services. It is also a 'Controller', but with a difference that Rest Controller returns Data, while Controller returns a View of 'Model-View-Controller' architecture.

  15. How to Use REST APIs

    2. Applications in the Cloud. REST API calls are ideal for cloud applications due to their statelessness. If something goes wrong, you can re-deploy stateless components, and they can grow to manage traffic shifts. 3. Cloud Computing. An API connection to a service requires controlling how the URL is decoded.

  16. Restful Web Services Tutorial in Java

    Restful Web Services. Restful Web Services is a stateless client-server architecture where web services are resources and can be identified by their URIs. REST Client applications can use HTTP GET/POST methods to invoke Restful web services. REST doesn't specify any specific protocol to use, but in almost all cases it's used over HTTP/HTTPS.

  17. REST API Tutorial

    REST API Tutorial - REST Client, REST Service, and API Calls Explained With Code Examples. Vaibhav Kandwal ... REST API: this defines the endpoint and methods allowed to access/submit data to the server. We will talk about this in great detail below. Other alternatives to this are: GraphQL, JSON-Pure and oData. ...

  18. XML Examples

    Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.

  19. Does REST use XML?

    VDOM DHTML tml>. Does REST use XML? - Quora. Something went wrong. Wait a moment and try again.

  20. Introducing Python in Excel: The Best of Both Worlds for Data Analysis

    To see examples of machine learning and visualization, and stay informed of updates, visit the Excel.... Seamlessly aggregate and visualize your data with Python in Excel. Collaborate easily. Share workbooks and Python analytics in your favorite tools like Microsoft Teams and Microsoft Outlook. Collaborate seamlessly with comments and ...

  21. HowTo

    In this post, we will go step by step through an example to build out a RESTful web service with XML request and response payload. Check out the complete project on Anypoint Exchange. Pre-requisites: Sign up for an Anypoint Platform Account. Download Anypoint Platform Design Tool - MuleSoft Anypoint Studio.