MultipartFile is empty during rest api POST of Javascript file upload

I am using React JS to upload a file. This is the file array object i am trying to send as a POST request:

I am using React JS to upload a file. This is the file array object i am trying to send as a POST request:

I am trying to submit a POST request via axios:

The file i am sending is not empty: 

But as soon as the debugged code reaches the back-end, (REST API) the MultipartFile[] is empty 

I wonder why.. Maybe i am missing some configuration here? Please help! Thank you!

GraphQL vs REST: putting REST to rest

GraphQL vs REST: putting REST to rest

When you need to build an API, your mind will likely jump to REST, the de facto standard for API creation. However, this is about to change with GraphQL, as its popularity quickly rises.

When you need to build an API, your mind will likely jump to REST, the de facto standard for API creation. However, this is about to change with GraphQL, as its popularity quickly rises.

Not everyone fully understands yet what GraphQL is all about, or why it's being declared as the successor of REST, and that's exactly what I'll clear up in this article. Here I'll show off GraphQL's main features and the advantages that it has over REST, highlighting a few points in which both differ.

The goal is to provide a brief explanation to anyone who still hasn't got to know GraphQL, and clarify exactly what it does better than REST, for those who are still skeptic about this technology.

Let's start with the very basics.

What is GraphQL?

GraphQL is a query language for APIs that enables declarative data fetching in order to give the client the power to specify exactly the data that is needed from the API.

A question that I see asked a lot is:

Why was GraphQL created when we already have REST?
There are two main reasons why companies such as Facebook, Netflix and Coursera started developing alternatives to REST:

1. In the early 2010s there was a boom in mobile usage, which led to some issues with low-powered devices and sloppy networks. REST isn't optimal to deal with those problems;

2. As mobile usage increased, so did the number of different front-end frameworks and platforms that run client applications. Given REST's inflexibility, it was harder to develop a single API that could fit the requirements of every client.

If we go even further, we realize that the main reason why an alternative solution was identified was because most of the data used in modern web and mobile applications has a graph shape. For instance, newspieces have comments, and those comments may have features such as likes or spam flags, which are created or reported by users. This example describes how a graph looks like.

Consequently, Facebook started developing GraphQL. At the same time, Netflix and Coursera were also working on alternatives themselves. After Facebook open-sourced GraphQL, Coursera dropped their efforts and adopted the new tech. Netflix, however, continued developing their own REST alternative and later open sourced Falcor.

What GraphQL isn't

Now that we know what GraphQL is, I want to clarify what it is not, as I feel that there's still some confusion about it.

Firstly, it doesn't have anything to do with databases. It isn't an alternative to SQL or a brand new ORM.

Secondly, it isn't a REST replacement, but an alternative. You don't have to pick between one and the other, they can happily co-exist in the same project.

Last but not least, GraphQL isn't complicated or scary. It's quite easy to understand its declarative nature and exactly how it's possible to take the best from it.

GraphQL in context

Before moving on to the comparison with REST, I'll go through a simple GraphQL query where we can fetch a user as well as his or her name and age:

query {
  user {
    name
    age
  }
}

And the JSON response we'll get from it:

{
  "user": {
    "name": "Johnathan Joestar",
    "age": 27
   }
}

As I stated previously, GraphQL's declarative nature makes it incredibly easy to understand what's going on at all times, as we are basically writing JSON objects without the values.

Now that we have context, let's dive deep into GraphQL's features and the advantages that it has over REST.

GraphQL vs REST

In this section I'll go point by point through a practical example, comparing REST to GraphQL in order to demonstrate the flexibility of Facebook's query language.

Imagine that you have a blog, and you want the front page to show all the latest posts. In order to achieve this, you need to fetch the posts, so you will probably do something like this:

GET /api/posts

[
  {
    "title": "Cooler post",
    "subtitle": "...",
    "date": "07/05/2019"
  },
  {
    "title": "Cool post",
    "subtitle": "...",
    "date": "06/05/2019"
  }
]

But what if you want to see the author as well? You have three options to achieve this:

  • Fetch the authors from another resource:
GET /api/post/:id

{
  "post": {
    ...,
    "author": {
      "name": "Dio Brando"
    }
  }
}

  • Modify the resource to also return the author:
GET /api/posts

[
  {
    ...,
    "author": {
      "name": "Dio Brando"
    }
  },
  {
    ...,
    "author": {
      "name": "Johnathan Joestar"
    }
  }
]

  • Create a new resource that returns the posts with the author:
GET /api/postsWithAuthor

[
  {
    ...,
    "author": {
      "name": "Dio Brando"
    }
  },
  {
    ...,
    "author": {
      "name": "Johnathan Joestar"
    }
  }
]

Each of these approaches will create a problem of its own, so let's have a look at them one by one.

Under-fetching

With the first approach – fetching the authors from another resource – you'll end up with two server requests instead of one, and as you continue to scale, you may have even more requests to different endpoints in order to fetch all the needed data.

With GraphQL, this wouldn't happen. You would only have one request, and you wouldn't have to make multiple round trips to the server, as seen below:

query {
  posts {
    title
    subtitle
    date
    author {
      name
    }
  }
}

Over-fetching

Looking at the second approach – modifying the resource to also return the author – you can see that it solved the problem pretty nicely. However, changing a resource may have a secondary effect elsewhere on your application. More precisely, over-fetching.

Let's go back to your blog, but this time you also have a sidebar showing off the top monthly posts with their titles, subtitles and date, that is using the resource /api/posts. Since you modified the resource, now it also shows the author with it. However, we don't need it for the sidebar.

While this may not look like a problem, for users on limited data plans, having a website fetch useless data isn't ideal. Since GraphQL allows the client to only fetch the needed data, this problem wouldn't exist:

query {
  posts {
    title
    subtitle
    date
  }
}

Slow front-end development

Lastly, let's have a look at the last approach – creating a new resource that returns the posts with the author – since it's a common pattern to structure the endpoints according to the views in your project.

While this may solve problems such as the one described above, it also slows down the front-end development, since each specific view needs its specific endpoint. If at any point a view needs new data, the development has to slow down until the endpoint is updated.

Again, since GraphQL gives power to the client to fetch the needed data only, nothing slows down, as it's very simple to just add a new field to a query.

You would get from this:

query {
  posts {
    title
    subtitle
    date
  }
}

To this:

query {
  posts {
    title
    subtitle
    date
    author {
      name
    }
  }
}

REST vs GraphQL comparison recap

Let's just do a quick recap regarding the differences between REST and GraphQL:

  • GraphQL solves both over-fetching and under-fetching issues by allowing the client to request only the needed data;
  • Since the client now has more freedom in the fetched data, development is much faster with GraphQL than what it would be with REST.

Now we'll move on to a more in-depth overview of GraphQL's unique features.

GraphQL's features overview

Now that we know how it stacks up against REST, let's talk about some of the features that are unique to GraphQL.

Schema and Type System

GraphQL uses its own type system to define the schema of an API, with its syntax called Schema Definition Language (SDL). The schema serves as a contract between the server and the client to define how a client can access the data.

Once the schema is defined, the front-end and back-end teams can work independently, as the front-end can be easily tested with mock data. The front-end can also get useful information from the schema, such as its types, queries and mutations using GraphiQL or introspection. The schema also provides type safety, which is a plus for the front-end and back-end development, as it catches type errors early.

A schema example:

type User {
  name: String!
  age: Int
  posts: [Post!]!
}

type Post {
  title: String!
  subtitle: String!
  body: String!
  date: String!
  author: User!
}

type Query {
  users: [User!]!
  user(name: String!): User!
  posts: [Post!]!
  post(title: String!): Post!
}

type Mutation {
  createUser(name: String!, age: Int): User!
  createPost(title: String!, subtitle: String!, body: String!): Post!
}

GraphQL IDE

This is one of the most useful features of GraphQL development. A GraphQL IDE takes advantage of its self-documenting nature to make development a breeze.

Using GraphiQL or GraphQL Playground, you can just inspect your schema and even run queries and mutations to test out your API.

GraphQL Playground

Wrap up

GraphQL provides a smooth and fast development environment with its declarative and flexible nature, offering many improvements over REST. Despite being relatively new, it has already been adopted by companies such as Facebook, GitHub and many more .

It already has a large community and a vibrant ecosystem, and was already implemented in several popular languages, such as JavaScript, Go and Java.

While this post only dipped the toes into the ocean that is GraphQL, its website has a plethora of information and is an amazing place to learn and start using GraphQL.

With all this being said, it's not a perfect technology, and it still has a couple of drawbacks when compared with REST. But considering how young it is, the future looks incredibly bright for GraphQL.

What is REST API? | Restful Web Service

What is REST API? | Restful Web Service

In this post "Restful Web Service", you'll learn: What is Web services, what is API, What is REST API, How REST works and Implementation of REST API

What is REST API? | Restful Web Service

A REST API defines a set of functions to process requests and responses via HTTP protocol.

REST is used in mobile application as well as in web applications.


Consuming a RESTful API in React Application

Consuming a RESTful API in React Application

In this artilce will help you understand a few concepts you need to know so as to integrate a RESTful API in a React application

React is the one of the most popular frontend framework out there and more developers are increasing learning how to build real life applications with React. While learning React, you will eventually get to a point when you need to integrate APIs in your React application.

We will be building a simple contact list application to display the contact's name, email and we will store a catch phrase of a contact. We will make use of this endpoint, it contains a JSON dump of data needed for our contact list application.

Prerequisites
  • Basic knowledge of React (versions >=2.1.1)
  • Basic understanding of JavaScript
  • Basic understanding of APIs
  • Must have npm installed on your local machine (versions >= 5.2)
Setting up our environment

Install create-react-app

We will be creating our React Application using a neat tool called [create-react-app](https://morioh.com/p/ca6104fcb72a ""), this is a boilerplate that helps you set up a proper folder structure and assets binding for your React application. Run this command on your terminal.

    npm i create-react-app

Create a new Project

Next, we will create a new project using create-react-app. So you can switch into your preferred directory and run this command on your terminal.

    npx create-react-app react-api

npx is a tool to help execute packages, you can read more about it here

This will generate some scaffolds you need to get your React application running as quick as possible.

Next, run the application using the following command.

    npm start

This will automatically open http://localhost:3000 on your browser and you will get the default create-react-app homepage.

To access the application on any device you have connected on the same network, you can access it via http://<your-host-machine-ip>:3000 which will be shown to you in terminal.

Project setup

The next step is to modify the App.js file located in the src folder to look like this.

    // src/App.js

    import React, {Component} from 'react';

    class App extends Component {
      render () {
        return (
          // JSX to render goes here...
        );
      }
    }

    export default App;

If you noticed, we got rid of import logo from './logo.svg'; and import './App.css'; along with the JSX in the render() method because we will not be needing those in the course of this tutorial.

Setting up bootstrap

Next, we have to link bootstrap's CDN in the index.html file which can be found in the public folder.

    // public/index.html
    ...
    <head>
      ...
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
      ...
    </head>
    ...

When this is done we will render a bootstrap card in the App.js file by including this snippet in the return() method.

    // src/App.js

    import React, { Component } from 'react';

    class App extends Component {
      render() {
        return (
          <div class="card">
            <div class="card-body">
              <h5 class="card-title">Steve Jobs</h5>
              <h6 class="card-subtitle mb-2 text-muted">[email protected]</h6>
              <p class="card-text">Stay Hungry, Stay Foolish</p>
            </div>
          </div>
        );
      }
    }

    export default App;

If we reload our application the following changes will reflect showing the contact's name, email and catch phrase in a bootstrap card.

Feeding dynamic data from the API

Most modern web applications make use of the REST Protocol to communicate with each other. To achieve this, data is sent as JSON (JavaScript Object Notation) to the API. In turn, the API returns a JSON payload which can be static or dynamic data. Our application will parse and display the data in a presentable manner, making it appealing to the user.

Below is a typical JSON response from the contact list dump:

    [
      {
        "id": 1,
        "name": "Leanne Graham",
        "username": "Bret",
        "email": "[email protected]",
        "address": {
          "street": "Kulas Light",
          "suite": "Apt. 556",
          "city": "Gwenborough",
          "zipcode": "92998-3874",
          "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
          }
        },
        "phone": "1-770-736-8031 x56442",
        "website": "hildegard.org",
        "company": {
          "name": "Romaguera-Crona",
          "catchPhrase": "Multi-layered client-server neural-net",
          "bs": "harness real-time e-markets"
        }
      }
    ]

Creating a state

A state is simply an object that holds data pending to be rendered. This is where we will store the output from the API call.

    // src/App.js

    import React, { Component } from 'react';

    class App extends Component {

      state = {
        contacts: []
      }
      ...
    }

In the snippet above we have created a state to store the the output from our API request.

Calling the API

To fetch our contact list, we will use a componentDidMount() method in our App.js file. This method is executed immediately our component is mounted and we will also make our API request in that method.

    // src/App.js

    import React, { Component } from 'react'

    class App extends Component {
      ...
      componentDidMount() {
        fetch('http://jsonplaceholder.typicode.com/users')
        .then(res => res.json())
        .then((data) => {
          this.setState({ contacts: data })
        })
        .catch(console.log)
      }
      ...
    }

fetch('http://jsonplaceholder.typicode.com/users') will make a GET request to the endpoint .then(res => res.json()) parses the output to JSON, .then((data) => {this.setState({ contacts: data })}) sets the value of our state to the output from the API call and finally .catch(console.log) logs any error we get to the console.

Creating our contacts component

Next up, we will create a component to render the results as cards. To achieve this we will create a component by creating a new sub-folder named components in the src directory followed by creating a contacts.js file in the components directory by running:

    $ mkdir src/components
    $ touch src/components/contacts.js

The contents of the contacts.js component file will be the following:

    // src/components/contacts.js

    import React from 'react'

    const Contacts = ({ contacts }) => {
      return (
        <div>
          <center><h1>Contact List</h1></center>
          {contacts.map((contact) => (
            <div class="card">
              <div class="card-body">
                <h5 class="card-title">{contact.name}</h5>
                <h6 class="card-subtitle mb-2 text-muted">{contact.email}</h6>
                <p class="card-text">{contact.company.catchPhrase}</p>
              </div>
            </div>
          ))}
        </div>
      )
    };

    export default Contacts

The Contacts method accepts the contacts state we created earlier and then returns a mapped version of the state, which loops over the bootstrap card to insert the contact's name, email and catch phrase.

Rendering the contacts component

The final step to this application is to render our component in src/App.js . To do this, we have to import the component into App.js.

    // src/App.js

    import React, { Component } from 'react';
    import Contacts from './components/contacts';
    ...

Then in our render method we have to clear out whatever we had there before and pass our component along with the contacts state in there for it to be rendered.

    // src/App.js

    import React, { Component } from 'react'
    import Contacts from './components/contacts'

    class App extends Component {
      ...
      render() {
        return (
          <Contacts contacts={this.state.contacts} />
        )
      }
    }

    export default App
Running our application

If you don't already have your application running, you can run it by using the npm start command.

This will open your browser for you to view the application or show you some errors if you missed anything. You can visit directly by accessing http://localhost:3000 . If port 3000 is already in you you will be prompted to change the port.

Conclusion

In this tutorial, we built a simple contact list web page, that displayed contact details. We called a RESTful Api, and we displayed the response to the browser using React. We also covered how the componentDidMount() method works, how state works, how components works and how to fetch data from an API and parsing the data to a component.

You can learn more about React from the official documentation here. The source code to the application in this article is available on GitHub.