Demo Project 01 - simpleuserapi

  Let’s now build a Level 1 Upgraded REST API — a beginner-friendly Spring Boot CRUD project with:

✅ JSON input/output
@RequestBody & @PathVariable
✅ No DB (yet) – we'll use a simple in-memory List to store data
✅ Model + Controller + Service separation
✅ Clean and extendable folder structure


✅ Project Name: simpleuserapi

Goal:
A REST API to create, list, retrieve, and delete simple user objects.


✅ Folder Structure

simpleuserapi/
├── src/main/java/com/example/simpleuserapi/
│   ├── controller/UserController.java
│   ├── model/User.java
│   ├── service/UserService.java
│   └── SimpleUserApiApplication.java
└── src/main/resources/application.properties



✅ Step-by-Step Code


🧩 1. User Model

package com.example.simpleuserapi.model;

public class User {
    private Long id;
    private String name;
    private String email;

    public User() {}

    public User(Long id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }

    // Getters and Setters
    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 getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}



🔧 2. UserService – In-memory Logic

package com.example.simpleuserapi.service;

import com.example.simpleuserapi.model.User;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    private List<User> users = new ArrayList<>();
    private Long idCounter = 1L;

    public User createUser(User user) {
        user.setId(idCounter++);
        users.add(user);
        return user;
    }

    public List<User> getAllUsers() {
        return users;
    }

    public Optional<User> getUserById(Long id) {
        return users.stream().filter(u -> u.getId().equals(id)).findFirst();
    }

    public boolean deleteUser(Long id) {
        return users.removeIf(u -> u.getId().equals(id));
    }
}



🌐 3. UserController – REST Endpoints

package com.example.simpleuserapi.controller;

import com.example.simpleuserapi.model.User;
import com.example.simpleuserapi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }

    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id)
                .orElseThrow(() -> new RuntimeException("User not found"));
    }

    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Long id) {
        boolean removed = userService.deleteUser(id);
        return removed ? "User deleted" : "User not found";
    }
}



🚀 4. SimpleUserApiApplication.java

package com.example.simpleuserapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SimpleUserApiApplication {
    public static void main(String[] args) {
        SpringApplication.run(SimpleUserApiApplication.class, args);
    }
}



⚙️ 5. application.properties

(Leave empty or optionally enable CORS, logs, etc.)


✅ How to Run

./mvnw spring-boot:run


Test with Postman or curl:
# Create user
curl -X POST http://localhost:8080/api/users \
  -H "Content-Type: application/json" \
  -d '{"name": "Prakash", "email": "prakash@example.com"}'

# List all users
curl http://localhost:8080/api/users

# Get user by ID
curl http://localhost:8080/api/users/1

# Delete user
curl -X DELETE http://localhost:8080/api/users/1



✅ Next Step Options:

Would you like to:

  1. Add H2 or MySQL DB and JPA?

  2. Add DTO + Validation (@Valid, @NotNull)?

  3. Add Unit Tests?

  4. Convert it to a CRUD UI with Thymeleaf or Angular?


To build your Spring Boot project (e.g., simple_user_api) and generate a .jar file, follow these detailed steps.


✅ Step 1: Navigate to Project Folder

Open terminal or command prompt:

cd path/to/simple_user_api


Make sure your pom.xml is inside this folder.


✅ Step 2: Use Maven to Build the Project

Run this command:

./mvnw clean package


On Windows:

mvnw.cmd clean package


Or if Maven is installed globally:

mvn clean package



✅ What Happens:

  • clean → Deletes previous target/ build folder

  • package → Compiles code, runs tests, packages the app as a .jar

You should see output like:

[INFO] BUILD SUCCESS



✅ Step 3: Locate the JAR File

After a successful build, Maven creates the JAR file in:

simple_user_api/target/simple_user_api-0.0.1-SNAPSHOT.jar



✅ Step 4: Run the Project

Use the Java command to run the JAR:

java -jar target/simple_user_api-0.0.1-SNAPSHOT.jar


✅ Your Spring Boot app will start at:

http://localhost:8080/


If you have endpoints like /api/users, test using:

http://localhost:8080/api/users



✅ Optional: Skip Tests While Building

If you want to build faster and skip tests (if any), use:

./mvnw clean package -DskipTests



✅ Common Build Errors & Fixes

Error

Fix

JAVA_HOME not set

Set JAVA_HOME to point to JDK 17+

mvn not recognized

Use ./mvnw or install Maven

Compilation errors

Fix syntax/logic issues in code

Package mismatch

Ensure package ...; matches folder structure


Would you like help:

  • Converting it to a .war instead of .jar?

  • Creating a GitHub Actions CI pipeline?

  • Dockerizing it?

Let me know!

Here's a complete checklist of all the APIs in your simple_user_api project, along with manual testing steps using tools like Postman, curl, or your browser (for GET requests).


✅ API Endpoints (CRUD for User)

Method

Endpoint

Purpose

POST

/api/users

Create a new user

GET

/api/users

Get all users

GET

/api/users/{id}

Get a user by ID

DELETE

/api/users/{id}

Delete a user by ID


✅ Manual Testing Steps (Beginner Friendly)

🧪 Tool Options

  • Postman (recommended GUI tool)

  • curl (command-line)

  • Browser (only GET)


🔧 Step 1: Run Your App

From your project root:

java -jar target/simpleuserapi-0.0.1-SNAPSHOT.jar


Ensure it's running at:

http://localhost:8080


✅ 1. POST /api/users → Create User

Request:

  • Method: POST

  • URL: http://localhost:8080/api/users

  • Body (JSON):

{
  "name": "Prakash",
  "email": "prakash@example.com"
}


Using curl:

curl -X POST http://localhost:8080/api/users \
-H "Content-Type: application/json" \
-d '{"name": "Prakash", "email": "prakash@example.com"}'


Expected Response:

{
  "id": 1,
  "name": "Prakash",
  "email": "prakash@example.com"
}



✅ 2. GET /api/users → List All Users

Request:

  • Method: GET

  • URL: http://localhost:8080/api/users

Using curl:

curl http://localhost:8080/api/users


Expected Response:

[
  {
    "id": 1,
    "name": "Prakash",
    "email": "prakash@example.com"
  }
]



✅ 3. GET /api/users/{id} → Get User by ID

Example:

  • URL: http://localhost:8080/api/users/1

Using curl:

curl http://localhost:8080/api/users/1


Expected Response:

{
  "id": 1,
  "name": "Prakash",
  "email": "prakash@example.com"
}


If not found:

{
  "error": "User not found"
}



✅ 4. DELETE /api/users/{id} → Delete User

Example:

  • URL: http://localhost:8080/api/users/1

Using curl:

curl -X DELETE http://localhost:8080/api/users/1


Expected Response:

User deleted


If not found:

User not found



✅ Summary Table

Operation

URL

curl Example

Create User

POST /api/users

curl -X POST ...

List Users

GET /api/users

curl http://localhost:8080/api/users

Get User by ID

GET /api/users/1

curl http://localhost:8080/api/users/1

Delete User

DELETE /api/users/1

curl -X DELETE http://localhost:8080/api/users/1


✅ Want Enhancements?

I can also help you:

  • Add PUT for update

  • Add Swagger UI for visual testing

  • Add input validation (@NotBlank, @Valid)

  • Add custom error responses or exception handler

Let me know which you'd like next!



Distributed by Gooyaabi Templates | Designed by OddThemes