iTranslated by AI
Creating a REST API with Java, Spring Boot, PostgreSQL, and Spring Data REST
Finally, "docker-compose" is no longer in the title lol
TL;DR
- I'm doing this as a continuation or an addition to the previous article.
- Java + Spring Boot + PostgreSQL under docker-compose (JPA edition) | Junya Kitayama | zenn
- It's roughly the same as these articles:
- Creating a REST API incredibly easily with Spring JPA Data with REST and Lombok. | Qiita
- Thinking about a development environment with Spring Boot with Docker | tiqwablog
Preparing to use Spring Data REST
I briefly mentioned Spring Data REST in the article below, but it is a convenient package that generates all RESTful endpoints just by preparing Entities and Repositories.
- Trying to create a simple Web API with Java + Spring Boot under docker-compose | Junya Kitayama | zenn
So, even though I say "preparation," it just involves adding implementation 'org.springframework.boot:spring-boot-starter-data-rest' to server/build.gradle from the state of the previous article.
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-rest'
...
In Spring Initializr, it looks like this.
- Spring Initializr
No code changes are required from the state of the previous article. Amazing (pardon my elementary-level excitement).
Starting the Docker container, building with Gradle, starting the application, and sending requests
docker-compose up -d
# It takes a bit for the DB to start up and initialize, so wait a moment
docker-compose exec app bash
bash-4.4# sh gradlew build
...
BUILD SUCCESSFUL in 8m 41s
5 actionable tasks: 5 executed
# Verify it's created
bash-4.4# ls build/libs/
app-0.0.1-SNAPSHOT.jar
bash-4.4# java -jar build/libs/app-0.0.1-SNAPSHOT.jar
Once it's started, let's send a request.
$ curl http://localhost:8080/users -X GET
{
"_embedded" : {
"users" : [ {
"name" : "test",
"_links" : {
"self" : {
"href" : "http://localhost:8080/users/1"
},
"user" : {
"href" : "http://localhost:8080/users/1"
}
}
} ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/users"
},
"profile" : {
"href" : "http://localhost:8080/profile/users"
}
}
}
It works! Awesome!
You can also register data with a POST request.
$ curl http://localhost:8080/users -X POST -H "Content-Type:application/json" -d '{ "name":"foo" }'
{
"name" : "foo",
"_links" : {
"self" : {
"href" : "http://localhost:8080/users/2"
},
"user" : {
"href" : "http://localhost:8080/users/2"
}
}
}
$ curl http://localhost:8080/users -X POST -H "Content-Type:application/json" -d '{ "name":"bar" }'
{
"name" : "bar",
"_links" : {
"self" : {
"href" : "http://localhost:8080/users/3"
},
"user" : {
"href" : "http://localhost:8080/users/3"
}
}
}
Let's try a GET request again.
curl http://localhost:8080/users -X GET
{
"_embedded" : {
"users" : [ {
"name" : "test",
"_links" : {
"self" : {
"href" : "http://localhost:8080/users/1"
},
"user" : {
"href" : "http://localhost:8080/users/1"
}
}
}, {
"name" : "foo",
"_links" : {
"self" : {
"href" : "http://localhost:8080/users/2"
},
"user" : {
"href" : "http://localhost:8080/users/2"
}
}
}, {
"name" : "bar",
"_links" : {
"self" : {
"href" : "http://localhost:8080/users/3"
},
"user" : {
"href" : "http://localhost:8080/users/3"
}
}
} ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/users"
},
"profile" : {
"href" : "http://localhost:8080/profile/users"
}
}
}
Of course, you can also GET only a specific piece of data by specifying the ID in the URI.
$ curl http://localhost:8080/users/3 -X GET
{
"name" : "bar",
"_links" : {
"self" : {
"href" : "http://localhost:8080/users/3"
},
"user" : {
"href" : "http://localhost:8080/users/3"
}
}
}
You can also update data with a PUT request.
$ curl http://localhost:8080/users/3 -X PUT -H "Content-Type:application/json" -d '{ "name":"piyo" }'
{
"name" : "piyo",
"_links" : {
"self" : {
"href" : "http://localhost:8080/users/3"
},
"user" : {
"href" : "http://localhost:8080/users/3"
}
}
}
$ curl http://localhost:8080/users/3 -X GET
{
"name" : "piyo",
"_links" : {
"self" : {
"href" : "http://localhost:8080/users/3"
},
"user" : {
"href" : "http://localhost:8080/users/3"
}
}
}
Wow. This is really something.
Let's log into Adminer at http://localhost:9000 to see if the data is actually registered in the database.
It is registered! OK!
If you want to set up an extremely simple RESTful API, this might even be faster than Rails... lol
Troubleshooting: When registration via POST fails
Depending on the state of your code, you might get a 500 ERROR when sending a POST request.
You can check the nature of the error in the logs where the Spring Boot application is running by executing java -jar build/libs/app-0.0.1-SNAPSHOT.jar.
ERROR: relation "hibernate_sequence" does not exist
There is a possibility that the mapping for the @GeneratedValue in your Entity class against the PostgreSQL SERIAL column is incorrect.
In the case of this code, please check the following part:
package com.example.app.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
// Check if this is @GeneratedValue(strategy = GenerationType.IDENTITY)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
protected User() {}
public User(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return String.format("{id:%d,name:%s}", id, name);
}
}
- How to handle "relation "hibernate_sequence" does not exist" with PostgreSQL + JPA | Qiita
- How to generate primary keys using @GeneratedValue | Qiita
ERROR:permission denied for sequence user_id_seq
In this setup, we created a user called appuser to connect from the app server to PostgreSQL. If appuser does not have SELECT permission on SEQUENCES, an error will occur when issuing an id increment for the SERIAL column.
In the case of this code, please check the following part:
CREATE ROLE appuser WITH LOGIN PASSWORD 'apppass';
GRANT SELECT,UPDATE,INSERT,DELETE ON ALL TABLES IN SCHEMA public TO appuser;
-- Check if the line below is correctly included
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO appuser;
- sql - ERROR: permission denied for sequence cities_id_seq using Postgres | Stack Overflow
Note that if you edit the queries under forDocker/db/initdb, since this docker-compose.yml has a docker volume assigned, you can have it re-executed by deleting dbvol with docker volume rm ....
The repository for this article can be found here.
References
- Creating a REST API incredibly easily with Spring JPA Data with REST and Lombok. | Qiita
- Customizing HTTP Endpoints in Spring Data REST
- Thinking about a development environment with Spring Boot with Docker | tiqwablog
- Tutorial | React.js and Spring Data REST | Spring
- Trying Spring Data REST with Spring Boot | abcdefg.....
Discussion
「今回のコードであれば以下の部分を確認してみてください。」とか
偉そうに書いてるけど今回の記事を書き始めてから前回の記事を修正したのは内緒です(これが原因でハマッた人がいたらごめんなさい、のでトラブルシュートとして書きました🙇♂️)
タイトル制限とりあえず近いうちに+10字します…😹
@catnose さん
ありがとうございます!私ももうちょっとシンプルにタイトルつけるようにします 🙇♂️