REST API
What is API
API is short for “Application Programming Interface”.
This helps to use prepared functions from programs.
What is REST
REST, short for “Representational State Transfer,” is an architectural style for designing networked applications.
There are 4 structural principles for REST.
- Statelessness: Do not manage the state, such as sessions. The exchanged information should be self-contained and interpretable on its own.
- Uniform Interface: Define and share a system of commands for manipulating information, such as the HTTP methods like GET or POST.
- Resource Identification: All information is uniquely identified using a generic syntax, such as URLs or URIs.
- Representation: The ability to include links within the information to other information or states, providing a means of navigating between resources.
Differences between RESTful API and other APIs
While APIs can be compatible with URLs, REST APIs specifically adhere to HTTP methods:
create: POST -> /UserInfo
update: PUT -> /UserInfo
delete: DELETE -> /UserInfo
get: GET -> /UserInfo
It’s important to note that RESTful APIs can also use these HTTP methods, differentiating mainly in URI structure and resource management. The focus on a uniform interface and resource identification sets REST apart in its design principles.
How to call API in HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index | MemberList</title>
</head>
<body>
<h1>MemberList</h1>
<a href="/creationForm.html">新規作成</a>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>グループ名</th>
<th>名前</th>
</tr>
</thead>
<tbody id="membersTable">
</tbody>
</table>
<script>
fetch('/api/members')
.then(response => response.json())
.then(data => {
const membersTable = document.getElementById('membersTable');
data.forEach(member => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${member.id}</td>
<td>${member.groupName}</td>
<td>${member.name}</td>
`;
membersTable.appendChild(row);
});
})
.catch(error => {
console.error('データの取得中にエラーが発生しました: ', error);
});
</script>
</body>
</html>
As the code above shows, fetch API with javaScript to get data when using REST API