📌 API Endpoints
- Next.js 앱 내부에서 HTTP 요청, 응답 처리 가능
- API Folder Convention은 API 엔드포인트의 그룹화와 체계적 관리에 유용
- api폴더 원하는 API 경로에 해당하는 폴더(여기에서는 users)를 생성하고 그 폴더 안에 route.tsx 파일 생성(page.tsx와 함께 있을 수 없음)
// src/app/api/users/route.tsx
import { NextRequest, NextResponse } from "next/server";
// GET 핸들러에 인자값이 없는 경우 응답 결과를 캐싱함
// export function GET() {
// 캐싱을 원하지 않는 경우 request 속성을 매개 변수로 추가
export function GET(request: NextRequest) {
return NextResponse.json([
{ id: 1, name: "a" },
{ id: 2, name: "b" },
]);
}
📌 Dynamic Routes와 API Endpoints
// src/app/api/users/[id]/route.tsx
import { NextRequest, NextResponse } from "next/server";
export function GET(
request: NextRequest, // 첫번째 인수 요청 처리
{ params }: { params: { id: number } } // 두번째 인수 params
) {
if (params.id > 10) {
return NextResponse.json({ error: "Use Not Found" }, { status: 404 }); // 에러 상태 코드 2번째 인수로 보냄
}
return NextResponse.json({ id: 1, name: "김일남" });
}
📌 POST
// src/app/api/users/route.tsx
// (생략)
export async function POST(request: NextRequest) {
const body = await request.json(); // request.json()은 promise를 리턴하기 때문에 async/await 사용
if (!body.name) {
return NextResponse.json({ error: "Name is required" }, { status: 404 });
}
return NextResponse.json({ id: 1, name: body.name });
}
/*
윈도우 curl을 이용한 요청 테스트
요청 명령 : curl -d "{""name"":""kim""}" -H "Content-Type: application/json" -X POST http://localhost:3000/api/users
요청 결과 : {"id":1,"name":"kim"}
*/
📌 PUT
- PUT : 전체 데이터 업데이트
- PATCH : 일부 데이터 업데이트
// src/app/api/users/[id]/route.tsx
export async function PUT(
request: NextRequest,
{ params }: { params: { id: number } }
) {
const body = await request.json();
if (!body.name) {
return NextResponse.json({ error: "Name is required" }, { status: 404 });
}
if (params.id > 10) {
return NextResponse.json({ error: "User Not Found" }, { status: 404 });
}
return NextResponse.json({ id: 1, name: body.name });
}
/*
윈도우 curl을 이용한 요청 테스트
요청 명령 : curl -d "{""name"":""lee""}" -H "Content-Type: application/json" -X PUT http://localhost:3000/api/users/1
요청 결과 : {"id":1,"name":"lee"}
*/
📌 DELETE
// src/app/api/users/[id]/route.tsx
export function DELETE(
request: NextRequest,
{ params }: { params: { id: number } }
) {
if (params.id > 10) {
return NextResponse.json({ error: "User Not Found" }, { status: 404 });
}
return NextResponse.json({});
}
/*
윈도우 curl을 이용한 요청 테스트
요청 명령 1 : curl -X DELETE http://localhost:3000/api/users/11
요청 결과 1 : {"error":"User Not Found"}
요청 명령 2 : curl -X DELETE http://localhost:3000/api/users/1
요청 결과 2 : {}
*/