Spring REST API -Part 2: Creating first API Response

Zia khalid
2 min readApr 15, 2017

Part 2: Creating first API Response

Note — Codes in the story is in continuation to the previous parts, so if you feel uncomfortable or disconnected please check the previous parts or navigate through git commit to have a better understanding.

In this part we will be creating a API which will give us lists of Java Topics.

Creating BaseEntity abstract class, which is MappedSuperclass for child entity classes, and will hold id’s (primary key) for child entity in database. Here we are choosing primary key generation strategies to be AUTO (persistence provider should pick an appropriate strategy for the particular database)

@MappedSuperclass
public class BaseEntity {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)

private final Long id;

protected BaseEntity() {
this.id = null;
}
}

Creating Topic entity which extends BaseEntity

@Entity
public class Topic extends BaseEntity {

private String name;
private int questionCount;

protected Topic() {
super();
}

public Topic(String name, int questionCount) {
this();
this.name = name;
this.questionCount = questionCount;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getQuestionCount() {
return questionCount;
}

public void setQuestionCount(int questionCount) {
this.questionCount = questionCount;
}
}

Creating TopicRepository which extends the CrudRepository interface.
CrudRepository provides sophisticated CRUD functionality for the entity class that is being managed.

import org.springframework.data.repository.CrudRepository;

public interface TopicRepository extends CrudRepository<Topic, Long>{

}

Loading database with dummy data
Creating DatabaseLoader which will load our database with dummy data.

@Component
public class DatabaseLoader implements ApplicationRunner{

private TopicRepository topics;
@Autowired
public DatabaseLoader(TopicRepository topics) {
this.topics = topics;
}

@Override
public void run(ApplicationArguments args) throws Exception {

ArrayList<Topic> bunchOfTopic = new ArrayList<Topic>();

String[] buzzWords = {"Multi Threading", "Inner Classes", "Collections", "Generics", "Development", "JVM"};

//Using java 8 features (stream, lambda)
IntStream.range(0,10).forEach(it -> {
String buzzWord = buzzWords[it % buzzWords.length];
Topic topic = new Topic(buzzWord, (it % buzzWords.length));
bunchOfTopic.add(topic);
});

topics.save(bunchOfTopic);
}
}

Commit
Here you can see the commit of all this changes:

https://github.com/ziakhalid/spring-rest-sample/commit/4e6bf81635097e5d35cf1ba8f5317823d68a18dc

HIT Run :)

http://localhost:8080/topics

Output

If you find something to improve please let me know, I will try my best to improve this story.

If this article was helpful to you, please do hit the 💚 button below. Thanks!

See you in the next story!

Next Article

Part 3: Spring Security (Basic Authentication)

--

--