Developing a web API with SPRING and ANGULAR.JS (Part 1)

In this post we will discuss how we can develop a web API in Spring and then access it using Angular.js. Additionally we will be using Angular Material to give our frontend application a nice look and feel.

This article uses following Versions:

  • Spring: 4.2.3.RELEASE
  • Spring Security: 4.0.3.RELEASE
  • Angular.js: 1.4.7

Creating web applications using Spring has been discussed in much details across multiple forums, blogs, articles and even Videos. They usually use some kind of view technology JSF or JSP together with a templating engine for the view such as Thymeleaf or Primefaces.

In this article however we will focus on separating the backend application from the view. For this we will implement a REST API using Spring and then a frontend application using Angular.js. The communication between these two will be implemented with AJAX calls to the server.

Setup

In the first step we will set up our Spring web application. For this we will first declare the required dependencies in our POM file.

Next we will need to create our Spring configuration files.

  • SecurityWebApplicationInitializier
  • DispatcherServletInitializer
  • MvcConfiguration
  • RootConfiguration
  • WebSecurityConfigurerAdapter

We will do without XML configuration and rather configure everything in a nice JAVA fashion.

Let’s start with the simple ones:

As you can see these two only need to be present. No additional configuration required.  Now to something a little bit more interesting:

Again nothin terribly interesting

Here we define a few slightly more interesting things:

We define where our views will reside and what suffix they will have. Additionally we define the path of our static resources will be. We only require this in case we want to provide some default views for the server when accessing the API server directly. This could be an API documentation. For now we will not define any views as we want to access the application via an API from a JavaScript frontend. Finally we need to configure Spring security which looks like following and dis fairly straight forward.

 

Here we define a custom user details service,  which will load our user from the backend and provide it for the authentication process. We then define a password encoder so we do not store the passwords in plain text. Read more about Spring password encoding here.

Up until now this is a standard configuration for a Spring  MVC application with spring security, and can be used for exactly that. For our purpose this is all we need, for the only difference in our API to a standard web application is, that we will be serving and accepting JSON data instead of HTML views.

This concludes part 1, and in part 2 we will add some functionality to our API.

Tagged with: , , , , ,

Leave a Reply

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

*

fourteen − 6 =

*