API Architecture - Complete Java & Spring Boot Interview Guide

Master API Architecture with client-server architecture, layered architecture, API Gateway, microservices, internal working, Spring Boot implementation, production architecture, common mistakes, best practices, and interview questions.

What is API Architecture?

API Architecture defines how API requests travel through an application from the client until data is returned.

It explains:

  • How requests are received
  • Where authentication happens
  • Where business logic executes
  • How data is retrieved
  • How responses are generated
  • How APIs scale in production

A good API architecture is:

  • Scalable
  • Secure
  • Maintainable
  • Testable
  • Loosely coupled
  • Easy to extend

Why Do We Need API Architecture?

Without architecture:

flowchart TD
    C["Client"] --> DB["Database"]

Problems:

  • No security
  • Business logic inside UI
  • Difficult maintenance
  • No monitoring
  • Tight coupling
  • Impossible to scale

Proper API architecture introduces layers.

flowchart TD
    C["Client"] --> API["API"] --> BL["Business Logic"] --> DB["Database"]

Each layer has one responsibility.


Evolution of API Architecture

Stage 1

Direct Database Access

flowchart TD
    DA["Desktop App"] --> DB["Database"]

Problems

  • Tight coupling
  • Security risks
  • Difficult upgrades

Stage 2

Three-Tier Architecture

flowchart TD
    P["Presentation"] --> BL["Business Layer"] --> DB["Database"]

Stage 3

REST APIs

flowchart TD
    C["Client"] --> RA["REST API"] --> BS["Business Service"] --> DB["Database"]

Stage 4

Microservices

flowchart TD
    M["Mobile"] --> GW["Gateway"]
    GW --> CS["Customer Service"]
    GW --> OS["Order Service"]
    GW --> PS["Payment Service"]
    GW --> IS["Inventory Service"]

Each service owns its own business capability.


High-Level API Architecture

flowchart TD
    WEB["Web"] & MOB["Mobile"] & PAR["Partner"] & ADM["Admin"] --> LB["Load Balancer"]
    LB --> GW["API Gateway"]
    GW --> AUTH["Authentication"]
    GW --> RL["Rate Limit"]
    GW --> LOG["Logging"]
    AuthRlLog["AUTH & RL & LOG"] --> CS["Customer Service"]
    AuthRlLog["AUTH & RL & LOG"] --> OS["Order Service"]
    AuthRlLog["AUTH & RL & LOG"] --> PS["Payment Service"]
    CS --> CR["Customer Repository"] --> CDB["Customer DB"]
    OS --> OR["Order Repository"] --> ODB["Order DB"]
    PS --> PR["Payment Repository"] --> PDB["Payment DB"]

API Request Lifecycle

Consider:

GET /customers/101

Request flow

Client

↓

DNS

↓

Load Balancer

↓

API Gateway

↓

Authentication

↓

Authorization

↓

Customer Controller

↓

Customer Service

↓

Customer Repository

↓

Database

↓

Repository

↓

Service

↓

Controller

↓

Gateway

↓

Client

Every production REST API follows a similar pipeline.


Responsibilities of Each Layer

Layer Responsibility
Client Sends requests
Load Balancer Distributes traffic
API Gateway Routing, authentication, throttling
Controller Accepts HTTP requests
Service Business logic
Repository Database access
Database Persistent storage

Spring Boot Layered Architecture

Controller

↓

Service

↓

Repository

↓

Database

Each layer performs only one responsibility.


Controller Layer

Receives HTTP requests.

@RestController
@RequestMapping("/customers")
public class CustomerController {

    private final CustomerService customerService;

    public CustomerController(
            CustomerService customerService) {

        this.customerService = customerService;
    }

    @GetMapping("/{id}")
    public Customer getCustomer(
            @PathVariable Long id) {

        return customerService.getCustomer(id);
    }

}

Responsibilities

  • Request mapping
  • Validation
  • Calling service
  • Returning HTTP response

Business logic should never be placed here.


Service Layer

Contains business rules.

@Service
public class CustomerService {

    private final CustomerRepository repository;

    public CustomerService(
            CustomerRepository repository) {

        this.repository = repository;
    }

    public Customer getCustomer(Long id) {

        return repository.findById(id)
                .orElseThrow(() ->
                        new RuntimeException(
                                "Customer Not Found"));
    }

}

Responsibilities

  • Business validation
  • Calculations
  • Calling multiple repositories
  • Transactions
  • Calling external APIs

Repository Layer

Responsible for persistence.

@Repository
public interface CustomerRepository
        extends JpaRepository<Customer, Long> {
}

Responsibilities

  • SQL generation
  • CRUD
  • Database interaction

Entity Layer

@Entity
public class Customer {

    @Id
    private Long id;

    private String name;

    private String city;

}

Maps Java objects to database tables.


Complete Flow

Suppose user requests

GET /customers/10

Step 1

Browser

↓

CustomerController

Step 2

CustomerController

↓

CustomerService

Step 3

CustomerService

↓

CustomerRepository

Step 4

CustomerRepository

↓

MySQL

Step 5

Database returns

Customer

Step 6

Spring Boot converts

Customer

into

{
  "id":10,
  "name":"John",
  "city":"Dallas"
}

Step 7

JSON returns to browser.


Internal Working Inside Spring Boot

When request arrives

DispatcherServlet

↓

Handler Mapping

↓

Controller

↓

Service

↓

Repository

↓

Database

Response

Database

↓

Repository

↓

Service

↓

Controller

↓

Jackson

↓

JSON

↓

Client

Production Architecture

Large organizations rarely expose services directly.

Typical architecture

Internet

↓

Cloud Load Balancer

↓

API Gateway

↓

Authentication

↓

Rate Limiter

↓

Customer Service

↓

Kafka

↓

Inventory Service

↓

Payment Service

↓

Redis

↓

Database

Why API Gateway?

Gateway provides

  • Authentication
  • Authorization
  • SSL termination
  • Rate limiting
  • Request routing
  • Logging
  • Metrics
  • API aggregation

Instead of implementing these in every service.


Microservice Architecture

Customer API

↓

Customer Service

↓

Customer DB
Order API

↓

Order Service

↓

Order DB
Payment API

↓

Payment Service

↓

Payment DB

Each service owns:

  • Database
  • Deployment
  • Scaling
  • Business logic

Monolithic vs Microservice APIs

Monolith Microservice
Single application Multiple services
Single deployment Independent deployment
Shared database Independent databases
Easier initially Better scalability
Tight coupling Loose coupling

Synchronous Communication

Client

↓

Customer Service

↓

Order Service

↓

Payment Service

Caller waits until response returns.

Protocols

  • REST
  • gRPC

Asynchronous Communication

Order Service

↓

Kafka

↓

Notification Service

↓

Email Service

Caller does not wait.

Benefits

  • Better scalability
  • Loose coupling
  • Higher throughput

Common Architecture Patterns

Layered Architecture

Controller

↓

Service

↓

Repository

Most common Spring Boot architecture.


API Gateway Pattern

Single entry point.

Client

↓

Gateway

↓

Multiple Services

Backend for Frontend (BFF)

Mobile

↓

Mobile API
Web

↓

Web API

Each frontend has its own backend.


Aggregator Pattern

Gateway combines responses.

Customer

↓

Gateway

↓

Customer API

Order API

Payment API

↓

Single Response

Security Layer

Production requests usually pass through

HTTPS

↓

JWT Validation

↓

Authentication

↓

Authorization

↓

Controller

Never expose controllers directly without security.


Error Flow

Controller

↓

Service

↓

Repository

↓

Exception

↓

Global Exception Handler

↓

JSON Error

Example

{
  "timestamp":"2026-08-01T10:15:00Z",
  "status":404,
  "error":"Customer Not Found"
}

Advantages of Layered Architecture

  • Separation of concerns
  • Easier testing
  • Better maintainability
  • Reusable services
  • Easier debugging
  • Cleaner code
  • Independent development

Common Mistakes

Putting Business Logic in Controller

Bad

@GetMapping("/{id}")
public Customer getCustomer(Long id){

   // huge business logic

}

Business logic belongs in Service layer.


Repository Calling External APIs

Repositories should access databases only.


Controller Accessing Database Directly

Never do

Controller

↓

Database

Always

Controller

↓

Service

↓

Repository

One Service Calling Database of Another Service

Wrong

Order Service

↓

Customer Database

Correct

Order Service

↓

Customer API

Best Practices

  • Keep controllers thin.
  • Put business logic in services.
  • Repositories should access only databases.
  • Use DTOs for API responses.
  • Centralize exception handling.
  • Secure APIs at the gateway.
  • Monitor latency.
  • Use correlation IDs.
  • Log requests.
  • Design stateless APIs.

Production Example

Amazon checkout

Customer

↓

Gateway

↓

Cart Service

↓

Inventory Service

↓

Payment Service

↓

Shipping Service

↓

Notification Service

Each service is independently deployable.


Frequently Asked Interview Questions

1. What is API architecture?

API architecture defines how requests flow through an application from client to database and back.


2. What is layered architecture?

Separating application into Controller, Service, Repository and Database layers.


3. Why should controllers be thin?

Controllers should only handle HTTP requests.

Business logic belongs in the Service layer.


4. Why use Service layer?

To encapsulate business rules and keep applications maintainable.


5. Why shouldn't repositories call external APIs?

Repositories are responsible only for data persistence.


6. What is API Gateway?

A single entry point providing routing, authentication, rate limiting, monitoring and logging.


7. Why do microservices have separate databases?

To maintain loose coupling and independent deployments.


8. Difference between synchronous and asynchronous APIs?

Synchronous waits for a response.

Asynchronous continues processing without waiting.


9. What happens inside Spring Boot when a request arrives?

DispatcherServlet → Controller → Service → Repository → Database → JSON Response.


10. What is the biggest API architecture mistake?

Mixing responsibilities across layers and tightly coupling services.


Quick Revision

Topic Summary
Architecture Defines API request flow
Layers Controller → Service → Repository
Entry Point API Gateway
Business Logic Service Layer
Database Access Repository
Response JSON
Pattern Layered Architecture
Communication Sync / Async
Interview Frequency ⭐⭐⭐⭐⭐

Key Takeaways

  • API architecture separates responsibilities into well-defined layers.
  • Spring Boot applications typically follow Controller → Service → Repository architecture.
  • Production systems introduce API Gateways, Load Balancers, Authentication, Monitoring, and Microservices.
  • Controllers should remain thin while Services encapsulate business rules.
  • Proper API architecture improves scalability, maintainability, security, and testability.
  • Understanding API architecture is essential before learning API lifecycle, REST, HTTP internals, API Gateway, GraphQL, and production API design.