Easy Mobile Backend

Mihail Bohnearschi
6 min readMar 20, 2017

--

Ever been developing a personal application and suddenly you understand that you need a backend for that? Well I did, and this is my short tutorial on how to make a simple backend for your mobile application.

The language of choice will be Java (as it is in Android by default). This will narrow down the learning curve.

First of all we’ll need Spring Boot CLI which can easily be downloaded using homebrew.

$ brew tap pivotal/tap
$ brew install springboot

There are alternative installation options, feel free to choose any from here.

Also we have to install Heroku CLI for deploying our application

$ brew install heroku

Once we have installed the Spring Boot CLI and Heroku CLI, we can proceed to checking out our example project. We’ll create our REST API on top of it.
“cd” to the most suitable location for your project and then execute the code below.
Note that I named this project “endava-demo” but feel free to choose whatever name you like.

$ spring init --dependencies=web endava-demo

Now you can “cd” into your newly created project.

$ cd endava-demo

Right now our project contains only one file which is the Application class, but we’ll fix this soon.

To make this possible there’s a couple of dependencies we have to add. This project uses Maven so we’ll have to add the following lines to our pom.xml file and allow syncing of all dependencies.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1203-jdbc42</version>
</dependency>

Also we have to create a configuration Bean for our Database so add this class to our project

package com.example;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;@Configuration
public class DatabaseConfig {
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return new org.apache.tomcat.jdbc.pool.DataSource();
}
}

The last step to make our application aware of the database is editing the application.properties file which is located in the “resources” directory. In this file we specify our PostgreSQL URL (which is a path variable Heroku is aware about), the number of connections supported, naming and migration strategy.

spring.datasource.url=${JDBC_DATABASE_URL}
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.maxActive=10
spring.datasource.maxIdle=5
spring.datasource.minIdle=2
spring.datasource.initialSize=5
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.datasource.removeAbandoned=false

Now we are officially ready to start using our database, so let’s create a new package “domain” and add a “Task” class in it.

package com.example.domain;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;import javax.persistence.*;@Entity
@Table(name = "task_entity")
@JsonIgnoreProperties("id")
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private String description;
private String assignee;
private Long date;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
public Long getDate() {
return date;
}
public void setDate(Long date) {
this.date = date;
}
}

Now we have a data entity in our app but we need a CRUD layer that will allow us working with this entity. Our amazing application will work with PostgreSQL which is provided by default by Heroku as a data container. Of course we could use Hibernate ORM for this but then this article wouldn’t be called “Easy” so we’ll stick to JPA repositories (Java Persistence API).

Let’s create a new package “repository” and a “TaskRepository” class inside.

package com.example.repository;import com.example.domain.Task;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TaskRepository extends JpaRepository<Task, Long> {
}

Now we have an interface that provides access to our “Task” entities from the database.
However what I like to do is having another layer on top of JPA Repository to have more control of what happens with our entities so we’ll create another package “service” and create a “TaskService” class in it. Think of this as a data access service.

package com.example.service;import com.example.domain.Task;
import com.example.repository.TaskRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
@Service
@Transactional
public class TaskService {
private final TaskRepository taskRepository; @Autowired
public TaskService(TaskRepository taskRepository) {
this.taskRepository = taskRepository;
}
public void save(Task task) {
taskRepository.save(task);
}
public void delete(Task task) {
taskRepository.delete(task);
}
public void deleteAll() {
taskRepository.deleteAll();
}
public List<Task> getAll() {
return taskRepository.findAll();
}
}

Pay attention to our annotations in this class, by using @Service and @Transactional annotations we are letting Spring Framework know that this is a service and all operations have to be executed in transactions (which are rolled back in case something is wrong).
Another interesting annotation is the @Autowired one, this one allows dependency injection out of the box in Spring Framework.

Okay, so now we have our entity, and we have the service that allows executing various operations with it, the only thing left is the REST API, for this we’ll create another package “controller” and add a “TaskController” class in it. Here we’ll define our methods that will be accessible from our Android Device.

package com.example.controller;import com.example.controller.request.AddTaskRequest;
import com.example.controller.response.AddTaskResponse;
import com.example.database.domain.Task;
import com.example.service.TaskService;
import com.example.utils.ValidationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@RestController
public class TaskController {
private final TaskService taskService; @Autowired
public TaskController(TaskService taskService) {
this.taskService = taskService;
}
@RequestMapping(value = "/api/getTasks", method = RequestMethod.GET)
public List<Task> getTasks() {
return taskService.getAll();
}
@RequestMapping(value = "/api/addTask", method = RequestMethod.POST)
public AddTaskResponse addIncome(HttpServletResponse httpResponse,
@RequestBody(required = false) AddTaskRequest request) {
AddTaskResponse response = ValidationUtils.addTaskRequestValid(request);
if (!response.getSuccess()) {
return response;
}
taskService.save(request.getTask());
return response;
}
}

Observe the @RestController annotation, this tells our Spring Boot Framework that this class is a rest controller. The getTasks method is pretty clear since all it does is returning a list of tasks. The data returned as well as the request that we receive here is being automatically serialized/deserialized using Jackson so we’ll get a nice JSON list as a result. The addTask method is more complex. First of all it’s a POST method so it requires some data posed to it. We mark the request body as non required to handle the validation on our side cause else the Spring Framework will handle this errors.

For validation I have created a special class in “utils” package, you can add it as well.

package com.example.utils;import com.example.controller.request.AddTaskRequest;
import com.example.controller.response.AddTaskResponse;
import com.example.database.domain.Task;
public class ValidationUtils { public static AddTaskResponse addTaskRequestValid(AddTaskRequest request) {
AddTaskResponse response = new AddTaskResponse();
if (null == request) {
response.setSuccess(false);
response.setFailReason("Missing Request");
return response;
}
if (null == request.getTask()){
response.setSuccess(false);
response.setFailReason("Missing Task Object");
return response;
}
Task task = request.getTask();
if (isEmpty(task.getName())) {
response.setSuccess(false);
response.setFailReason("Missing Task Name");
return response;
}
if (isEmpty(task.getDescription())) {
response.setSuccess(false);
response.setFailReason("Missing Task Description");
return response;
}
if (isEmpty(task.getAssignee())) {
response.setSuccess(false);
response.setFailReason("Missing Task Assignee");
return response;
}
if (null == task.getDate()) {
response.setSuccess(false);
response.setFailReason("Missing Task Date");
return response;
}
response.setSuccess(true);
return response;
}
public static boolean isEmpty(String string) {
return null == string || string.isEmpty();
}
}

The request and response entities are listed below as well, I like to keep them in their own packages because over time when you have more requests this can become quite messy.

package com.example.controller.response;public class AddTaskResponse {    private Boolean success;
private String failReason;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getFailReason() {
return failReason;
}
public void setFailReason(String failReason) {
this.failReason = failReason;
}
}
package com.example.controller.request;import com.example.database.domain.Task;public class AddTaskRequest { private Task task; public Task getTask() {
return task;
}
public void setTask(Task task) {
this.task = task;
}
}

Also let’s go ahead and add a “HomeController” as well, that will resolve the calls to the index page.

package com.example.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
@ResponseBody
public String index() throws Exception {
return "Welcome Home";
}
}

Now we’re pretty much ready to get to the deploying of our amazing application.

First of all we have to init the git repository and add all our changes.

$ git init
$ git add .
$ git commit -m "first commit"

Once our repository is ready and all files are added we can proceed to creating our heroku application

First of all we have to login to heroku using this command

$ heroku login

Then we are ready to create our Heroku application using this command.

$ heroku create

This command will create a new application with randomly selected name (my was “whispering-brook-16019”), you can change it using Heroku CLI. I will rename it to endava-demo.

$ heroku apps:rename endava-demo

Now we can deploy our application using this command.

$ git push heroku master

You will see deploy logs in the terminal window and if everything will be okay, you’ll be able to run

$ heroku open

This will open up the browser and make a call to your application. You should see “Welcome Home” on your screen.

So there you have it, a simple REST API, now you can go ahead and test your Task methods that we added in TaskController by adding “/api/getTasks” to the base URL that opened up in the browser.

The full project can be found here.

For now it’s empty but I’ll use this sample in one of the next articles where we’ll be building the Android Application that will consume our newly created API. Stay tuned!

--

--