owned this note
owned this note
Published
Linked with GitHub
# RESTful APIs
RESTful APIs(Representational State Transfer APIs)是一種設計風格,用於建立網絡應用程序的API。它基於 REST 架構,將資源(Resource)視為網絡上的實體,並使用統一的接口進行資源的操作。
---
## RESTful APIs 的主要特點:
1. 資源導向:
RESTful APIs 將資源視為網絡上的實體,每個資源都有一個唯一的識別符號(URI),通過 URI 來訪問和操作資源。
2. 無狀態:
RESTful APIs 是無狀態的,意味著每個請求都是獨立的,服務器不需要保存任何關於客戶端的狀態。所有必要的資訊都包含在請求本身中,例如使用者身份驗證的令牌。
3. 統一的接口:
RESTful APIs 定義了一組統一的操作方法,包括 GET、POST、PUT、DELETE 等,用於對資源進行不同的操作。這些操作方法與 HTTP 協議的方法對應,使得 API 的使用更加直觀和一致。
4. 使用狀態碼:
RESTful APIs 使用 HTTP 狀態碼來表示請求的結果和錯誤,例如 200 表示成功,404 表示資源未找到,500 表示服務器錯誤等。這使得客戶端可以根據狀態碼來適當地處理和回應 API 的結果。
5. 支持不同的數據格式:
RESTful APIs 可以支持多種數據格式,例如 JSON、XML 等。通常使用 JSON 作為數據傳輸的標準格式,因其輕量且易於解析。
RESTful APIs 提供了一種簡單且具有彈性的方式來設計和開發網絡應用程序的 API。它具有可讀性高、可擴展性好、易於維護和測試等優點,因此成為了現代 Web 開發中常用的設計風格。
---
## 利用Restful架構,進行CRUD Operation
* 建立/新增 資料(Create):POST
* 讀取/查看 資料(Read):GET
* 更新/修改 資料(Update):PUT
* 刪除 資料(Delete):DELETE
### 前端呼叫API方式
#### AJAX
:::spoiler POST
```javascript=
function postData() {
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/users', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function () {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data); // 處理返回的資料
} else {
console.log('請求發生錯誤');
}
};
xhr.onerror = function (error) {
console.log(error); // 處理錯誤
};
xhr.send(JSON.stringify({ name: 'John', age: 30 }));
}
postData();
```
:::
:::spoiler GET
```javascript=
function getData() {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/users', true);
xhr.onload = function() {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data); // 處理返回的資料
} else {
console.log('請求發生錯誤');
}
};
xhr.onerror = function() {
console.log('請求發生錯誤');
};
xhr.send();
}
getData();
```
:::
:::spoiler PUT
```javascript=
function updateData() {
const xhr = new XMLHttpRequest();
xhr.open('PUT', 'https://api.example.com/users/1', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data); // 處理返回的資料
} else {
console.log('請求發生錯誤');
}
};
xhr.onerror = function() {
console.log('請求發生錯誤');
};
xhr.send(JSON.stringify({ name: 'John Doe', age: 35 }));
}
updateData();
```
:::
:::spoiler DELETE
```javascript=
function deleteData() {
const xhr = new XMLHttpRequest();
xhr.open('DELETE', 'https://api.example.com/users/1', true);
xhr.onload = function () {
if (xhr.status === 200) {
console.log('資源已成功刪除');
} else {
console.log('刪除資源時出現錯誤');
}
};
xhr.onerror = function (error) {
console.log(error); // 處理錯誤
};
xhr.send();
}
deleteData();
```
:::
#### JQuery-AJAX
:::spoiler POST
```javascript=
function postData() {
$.ajax({
url: 'https://api.example.com/users',
type: 'POST',
data: JSON.stringify({ name: 'John', age: 30 }),
contentType: 'application/json',
success: function (data) {
console.log(data); // 處理返回的資料
},
error: function (error) {
console.log(error); // 處理錯誤
}
});
}
postData();
```
:::
:::spoiler GET
```javascript=
function getData() {
$.ajax({
url: 'https://api.example.com/users',
type: 'GET',
success: function (data) {
console.log(data); // 處理返回的資料
},
error: function (error) {
console.log(error); // 處理錯誤
}
});
}
getData();
```
:::
:::spoiler PUT
```javascript=
function updateData() {
$.ajax({
url: 'https://api.example.com/users/1',
type: 'PUT',
data: JSON.stringify({ name: 'John Doe', age: 35 }),
contentType: 'application/json',
success: function (data) {
console.log(data); // 處理返回的資料
},
error: function (error) {
console.log(error); // 處理錯誤
}
});
}
updateData();
```
:::
:::spoiler DELETE
```javascript=
function deleteData() {
$.ajax({
url: 'https://api.example.com/users/1',
type: 'DELETE',
success: function () {
console.log('資源已成功刪除');
},
error: function (error) {
console.log(error); // 處理錯誤
}
});
}
deleteData();
```
:::
#### fetch
:::spoiler POST
```javascript=
async function postData() {
try {
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: 'John', age: 30 }),
});
const data = await response.json();
console.log(data); // 處理返回的資料
} catch (error) {
console.log(error); // 處理錯誤
}
}
postData();
```
:::
:::spoiler GET
```javascript=
async function fetchData() {
try {
const response = await fetch('https://api.example.com/users', {
method: 'GET',
});
const data = await response.json();
console.log(data); // 處理返回的資料
} catch (error) {
console.log(error); // 處理錯誤
}
}
fetchData();
```
:::
:::spoiler PUT
```javascript=
async function updateData() {
try {
const response = await fetch('https://api.example.com/users/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: 'John Doe', age: 35 }),
});
const data = await response.json();
console.log(data); // 處理返回的資料
} catch (error) {
console.error(error); // 處理錯誤
}
}
updateData();
```
:::
:::spoiler DELETE
```javascript=
async function deleteData() {
try {
const response = await fetch('https://api.example.com/users/1', {
method: 'DELETE',
});
if (response.ok) {
console.log('資源已成功刪除');
} else {
console.log('刪除資源時出現錯誤');
}
} catch (error) {
console.error(error); // 處理錯誤
}
}
deleteData();
```
:::
#### axios
:::spoiler POST
```javascript=
async function postData() {
try {
const response = await axios.post('https://api.example.com/users', { name: 'John', age: 30 });
console.log(response.data); // 處理返回的資料
} catch (error) {
console.log(error); // 處理錯誤
}
}
postData();
```
:::
:::spoiler GET
```javascript=
async function getData() {
try {
const response = await axios.get('https://api.example.com/users');
console.log(response.data); // 處理返回的資料
} catch (error) {
console.log(error); // 處理錯誤
}
}
getData();
```
:::
:::spoiler PUT
```javascript=
async function updateData() {
try {
const response = await axios.put('https://api.example.com/users/1', { name: 'John Doe', age: 35 });
console.log(response.data); // 處理返回的資料
} catch (error) {
console.log(error); // 處理錯誤
}
}
updateData();
```
:::
:::spoiler PATCH(單一資料更新使用)
```javascript
async function updateData() {
try {
const response = await axios.patch('https://api.example.com/users/1', { name: 'John Doe', age: 35 });
console.log(response.data); // 處理返回的資料
} catch (error) {
console.log(error); // 處理錯誤
}
}
updateData();
```
:::
:::spoiler DELETE
```javascript=
async function deleteData() {
try {
const response = await axios.delete('https://api.example.com/users/1');
console.log('資源已成功刪除');
} catch (error) {
console.log(error); // 處理錯誤
}
}
deleteData();
```
:::
### 後端接收API方式(PHP)
:::spoiler POST
```PHP=
//方法ㄧ:接收表單形式提交的資料
$後端自定義變數 = $_POST['前端的值'];
//方法二:接收 POST 請求中的原始資料(如 JSON)
$postData = file_get_contents("php://input");
//將 JSON 格式的資料轉換成 PHP 陣列或物件形式的函式
$data = json_decode($postData, true);
$變數一 = $data['前端的值ㄧ'];
$變數二 = $data['前端的值二'];
```
:::
:::spoiler GET
```PHP=
$後端自定義變數 = $_GET['前端的值'];
```
:::
:::spoiler PUT 與 DELETE
```PHP=
$method = $_SERVER['REQUEST_METHOD'];
parse_str(file_get_contents('php://input'), $requestData);
if ($method === 'PUT') {
$後端自定義變數 = $requestData['前端的值];
// 使用 $userId 進行相應的處理
}
if ($method === 'DELETE') {
$userId = $requestData['id'];
// 使用 $userId 進行相應的處理
}
```
:::
###### 持續更新中!
###### 以上為自學中的筆記如有錯誤,懇請留言指正,感謝!