SightSpeak AI Blog

Home / AI Blog

Making Your Java API Better – Add a Database and Easy Docs

Hey community! API builders! Remember that first book API we made? It was cool, but kinda fake – no real way to save stuff. I wanted it to feel like a grown-up app. So one weekend, I rolled up my sleeves and added a real database plus some auto-magic docs. It took a couple "why isn't this working?!" moments, but man, the result? Your API suddenly feels legit. Let me walk you through what I learned, like I'm showing you over my shoulder at the coffee shop.

Step 1: Add a Database (Keep Stuff for Real)

No more pretend lists in our head. Let's make it save for real. I picked H2 – it's a tiny database that lives right in your computer's memory. No extra downloads, super easy.

First, go back to your project or start.spring.io and add two helpers: "Spring Data JPA" (that's for talking to databases) and "H2 Database." Save and let Maven grab them – you'll see a bunch of downloading in your IDE.

Now, let's tell our app what a "book" looks like. Make a new folder called "model" and add a file called Book.java:

import javax.persistence.*;

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private String title;

    // Simple getters and setters
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
}

This is like giving our database a blueprint for what books look like. @Entity says "this is a database thing," @Id marks our unique number for each book, and the getters/setters let other parts of our code read and change the info.

Now we need a helper to talk to the database. Make BookRepository.java:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
}

Look at that – it's empty! Spring sees we're using JpaRepository and gives us all the database magic for free. Find all books? Save a book? It's all there.

Step 2: Link It to Your Doors (Use Real Data)

Time to connect our controller to this database goodness. Open your BookController and add this line near the top, after the class starts:

import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    
    @Autowired
    private BookRepository bookRepository;

    // Our methods will go here
}

That @Autowired line is like saying "Hey Spring, please give me a BookRepository when you make this controller." Spring's like, "Sure thing!" and hands you one that's ready to roll.

Now update your GET method to use the real database:

@GetMapping
public List<Book> getBooks() {
    return bookRepository.findAll();
}

I forgot the @Autowired once and got a big red error. Felt dumb for about 30 seconds, then laughed because that's just coding life. The findAll() method is one of those freebies Spring gave us.

And update the POST to actually save:

@PostMapping
public Book addBook(@RequestBody Book book) {
    return bookRepository.save(book);
}

Notice we changed String to Book and bookName to book. Now in Postman, send {"title": "Brave New World"} as JSON. Then hit GET /books – boom, your book is there with an ID number! Magic. Thanks for reading, More awesome blogs are on the way with SightSpeak AI, so stay tuned for what’s next!

To actually see inside our database, add these lines to your application.properties file:

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb

Now go to localhost:8080/h2-console in your browser. Log in with "H2" for both username and password. Click "Connect" and you can see your books living in there. I stared at that screen for way too long the first time, grinning like a kid.

Step 3: Add Auto-Docs (No More Writing Notes)

Writing documentation is the worst. Swagger fixes that – it makes beautiful docs automatically. Add this to your pom.xml file, in the section:

<dependency>
    <groupId>org.springdocgroupId>
    <artifactId>springdoc-openapi-starter-webmvc-uiartifactId>
    <version>2.0.2version>
dependency>

Save, let Maven download it, then restart your app. Go to localhost:8080/swagger-ui.html. Holy cow – there's your entire API documented with buttons to test everything! Try the POST right there to add a book, then the GET to see it. No Postman needed. I showed this to my coding buddy and he literally said "shut up" because it was too cool.

Step 4: Clean It Up and Share (Put It Online)

Want to make it even nicer? Add some basic error handling. Wrap your methods like this:

@GetMapping
public List<Book> getBooks() {
    try {
        return bookRepository.findAll();
    } catch (Exception e) {
        return new ArrayList<>(); // Return empty list if something breaks
    }
}

This way if the database hiccups, your API doesn't crash – it just says "no books right now."

To share with the world, I love Heroku. Make a GitHub repo, push your code, then connect it to Heroku. Add a file called Procfile (no extension) with:

web: java -jar target/*.jar

My first deploy failed because I forgot to tell Heroku about the database, but a quick settings tweak and it was live. Share that URL with friends – watch their faces when they add a book and see it stick around!

You Did It – From Baby Steps to Real Deal!

Take a moment and look at what you built: a real API that saves data, has auto-docs, and can live online. I learned more from the "doh!" moments than the smooth parts, so don't sweat the bugs – they're your teachers.

What's next? Maybe add user login? Or pictures of book covers? Or deploy to a different spot? Drop your ideas or questions in the comments – I love geeking out about this stuff. You're crushing it, seriously. High-five through the screen!

Published: September 22, 2025

By: puja.kumari