Application
- Set of rules and protocols (명세서) that allows two different software programs to communicate with each other
- A mapping of HTTP URL endpoints and HTTP Request Methods to specific actions
- Tells u how to make requests and how data coming back is structured
- Interface
- refers to a point of contact or a boundary where two things meet
- diagram
Advantages
- Abstraction - Classes & Interfaces
- Hides the specific implementation details and shows only the necessary data
sendMessage(String userId, String text)
→ we don’t care if it useskafka
, a database, or whatever. We just use it.
- Encapsulation
- Can protect the implementation details so they are untouched from the outside
- Managing System Boundaries
- Lowers coupling between modules and ensures structural independence.
- A Tool for Collaboration
- The API specification acts as a contract or promise between teams.
- JSON format → shared structure for data
- iOS, Android, and Web applications can all use the exact same JSON structure to talk to a backend server
- Enhancing Reusability
- Allows functionality to be reused as a unit in your project (e.g., Service, Util).
- Example: collecting addresses for user sign-ups or shipping forms
- If each project formats the address differently, it becomes a nightmare to analyze + process that data accurately
- Wrong approach: Each frontend client formats addresses independently, and the backend uses rigid, hardcoded logic to interpret them. Result: chaotic + unpredictable formats, db issues, and unreliable api
- Correct approach: The backend provides a common, reusable API, such as
AddressFormatter.format(region, district)
& the frontend simply sends the raw data (e.g., the city and district names) and lets the backend handle all the formatting.
Tips
- When designing an API, always ask yourself: “From the user’s perspective, what is the essential information they need to use this method?”
- You must hide any information that should never be exposed externally, such as your database structure, internal encryption methods, etc.
- For team collaboration, sharing the API specification via documentation tools like Swagger or
OpenAPI
is the standard practice- 개발자는 문서 쓰는 능력이 매우 중요함
- In REST API design, remember that the URL, HTTP method, response codes, and body structure are all integral parts of the API contract.
- 메서드 이름만 보고 뭔지 알아야 좋은 디자인임
- Even if you don’t use the
interface
keyword, a controller endpoint (e.g.,@GetMapping
) still functions as a type of API contract.
Basic Principles for Building APIs
Summary ⭐
Principle | Description | Example |
---|---|---|
Consistency | Design URIs and responses based on unified, predictable rules. | A request to GET /users/1 should always return a response with the same data structure. |
Simplicity | The API should have a structure that is intuitive and easy to understand. | Keep URIs short and clear (e.g., use /users , not /getUserInfo ). |
Extensibility | Consider the possibility of future feature additions in your design. | Use optional parameters for filters and allow new fields to be added without breaking clients. |
Stability | Design a structure that can be operated long-term without breaking changes. | Announce the deprecation of a field long before you actually remove it. |
Consistency
Since APIs are used by multiple developers and teams simultaneously, their behavior and results must be predictable.
Consistent URI Patterns
URIs should be based on nouns that represent resources, and the same pattern should be used consistently across the entire service.
# 일관된 예
GET /users
GET /users/{id}
POST /users
PATCH /users/{id}
DELETE /users/{id}
# 나쁜 예: createUser, deleteUser 등 동사 혼용
GET /getUserById/1
POST /createUser
- they should also follow the same HTTP Request Methods conventions
Unified Response Field Naming Rules
- The naming convention for response fields must be unified into a single style within a project
- camelCase is recommended
Clear Distinction of Status Codes
Status codes must also be used consistently, and even similar types of errors should be clearly distinguished.
GET /users/1
→200 OK
GET /users/99999
→404 Not Found
POST /users
→201 Created
POST /users
(with a duplicate entry) →409 Conflict
Simply returning200 OK
for every situation, including errors, makes maintenance extremely difficult.- HTTP Fundamentals - Status Codes
Simplicity
- An API should hide its complex internal logic, providing an interface that is intuitive for external developers to understand and use
- Single Responsibility: Each API endpoint should be responsible for performing only one distinct function.
- Clear Error Handling: Exceptional situations must be handled clearly, and errors should be communicated back to the client using a standardized error format.
- Concise URIs: URIs should be as short and meaningful as possible.
// Bad URI
GET /api/v1/getUserInfoFromDb?id=1
// Good URI
GET /users/1
Extensibility
APIs inevitably evolve, with features being added or changed over time → needs flexible design
- Keep the base URI structure stable and extend functionality with new sub-resources or query parameters, rather than creating entirely new, overly specific URI paths.
- Clearly distinguish between required and optional parameters.
- Design the response structure so that it won’t break existing clients when new fields are added in the future.
GET /v1/users?status=active&role=admin&page=1&size=20&sort=createdAt,desc
This URL is designed for extensibility in several ways:
status
,role
: These are optional filtering parameters. New filters can be easily added in the future without breaking the API.page
,size
,sort
: These form a common pagination structure that can be reused across different API endpoints.- Including a version (
/v1/
): This is crucial for maintaining backward compatibility when you need to introduce breaking changes or add significant new features.
Stability
Public APIs must remain stable to avoid breaking connected systems. Frequent or unexpected changes can cause frontend errors, app crashes, or partner outages.
Example
- v1 Response:
{
"id": 1,
"name": "Alice",
"nickname": "Ali"
}
- v1.1 Response (This causes problems!)
{
"name": "Alice",
"id": 1,
"displayName": "Alice"
}
What Went Wrong
- Field order changed → Some clients rely on field order; changing it can break parsing.
nickname
removed → Clients accessing it may crash (e.g.,NullPointerException
).displayName
added → New field may break strict UI layouts or rendering.
Examples
🐣Spring & SpringBoot
Real World Use Case 1: Weather API
- real world use case example 1
- your own diary website + software OpenWeather
- you want ur app to automatically talk to OpenWeather’s server to bring their data into ur app ⇒ use an API
- OpenWeather has an API that tells you how you can interact with their services
- ex. if u pass in latitude & longitude of the location you’re interested in, they can give u the weather for that location
- U should then just make a request from our website through this API, and get the data back to integrate into ur app
Real World Use Case 2: mailchamp API
- real world use case example 2
- your newsletter + mailchimp
- u want to send ur email using mailchimp, and u want to send the email u collect each time on ur website into a database on ur mailchimp account ⇒ API
- MailChimp defines an API that tells u how u should structure ur POST requests & what kind of responses u’ll get back in different situations (maybe a success code like 200)
- example in code
app.get('/users', (req, res) => {
res.json([{ id: 1, name: 'Alice' }]);
});
- This API endpoint listens for a GET /users request and responds with a JSON list of users.
Types of APIs
- The term API doesn’t just mean HTTP. Anything that acts as an interface in a specific environment—like at the system level, within a programming language, or for a database—is also an API
- When integrating with external services, you must check for requirements like API key issuance, authentication methods (e.g., OAuth2, JWT), and rate limiting
-
- Most APIs provide official documentation, example code, and sample responses. The key to mastering any API is getting into the habit of reading the documentation thoroughly.
Operating System API (System API)
- The Operating System (OS) API is a system call interface that allows user programs to access hardware or kernel functions.
- Example: File System Access (☕Java)
Files.write(Paths.get("log.txt"), "Hello".getBytes());
- Internally, this wraps the OS’s
write()
system call. - In 🐧Linux, functions like
open
,read
,write
, andclose
exist for this purpose.
Operating System | API Package | Description |
---|---|---|
Windows | Win32 API | API for accessing Windows windows, files, and networks. |
Linux | POSIX API | System API for terminals, processes, threads, etc. |
Programming Language API
- Example: Java Collection(List) API
- It has methods like
.add()
and.clear()
& we don’t need to know how they are implemented
- It has methods like
Language | Representative API | Description |
---|---|---|
Java | JDK API (java.util, java.io) | All classes provide API documentation based on Javadoc. |
Python | Built-in modules (os, math) | Composed of standard, built-in APIs. |
JavaScript | DOM API, Web API | APIs provided by the browser (e.g., document.querySelector() ). |
Database API (DB API)
- An API that allows an application to communicate with a database.
- Example: Java JDBC API
- DB APIs are provided at various levels, from simple SQL execution to higher-level ORM (Object-Relational Mapping) abstractions.
Web API (HTTP API)
- API that enables communication over the internet and is the most popular and widely used type.
- Common architectural styles include REST API, GraphQL, and SOAP.
- Example: REST API Call (JavaScript Fetch)
- The client makes a request via HTTP.
- The server responds with data, often in JSON format.
fetch("https://api.weatherapi.com/v1/current.json?q=Seoul")
.then(res => res.json())
.then(data => console.log(data.current.temp_c));
- Just refer b ack to this: HTTP Fundamentals
API Architectures
Approaches of building APIs - distinct high-level patterns for designing APIs (how applications communicate)
Formatting API Requests
- In our own applications
- diagram
- we’ve been using private APIs for our applications
- private API = not publicly accessible over the internet. it’s exclusively serving our own frontend and not for someone else
- diagram
- But usually what we want to do is let our server talk to someone else’s server and interact with it
- diagram
- public API
- diagram
- API refers to a COLLECTION of API endpoints!!!!
Different ways to structure our API requests
BaseURL/Endpoint?query1=value&query2=value
Endpoint
- An endpoint is just a URL that your API listens to.
- endpoints are tied to URLs, but you don’t have to redirect to a webpage to use them
- When you make a request to an endpoint, the server decides how to respond — it might:
- Send back some data (like user info).
- Return a status code (like
200 OK
or404 Not Found
). - Return a new webpage
- documentation usually gives which endpoints to use and its purpose
- ex)
http://bored.api.lewagon.com/api/activity/
from bored.api- activity is an endpoint, gives u random activity
- ex)
Query
?query=value&query2=value
- A way to put a key/value pair into the URL when u want to give some additional information or some parameters to a request
- filtering/searching
- ex from bored.api
http://bored.api.lewagon.com/api/activity?key=5881028
- finding an activity by key
- add more queries with
&
Parameter
BaseURL/Endpoint/{path-parameter}
- after the url + endpoint, we can have this, which changes
- usually to find some specific resource that exists, that can identify a resource in the API