공부/코딩

와플 스튜디오 루키 과정 복습하기 - 4: create API in Next.js

고라닭 2025. 2. 23. 10:56

In this post, I practice to create API in Next.js and AWS S3.

 

I add GET function in route.ts which made last time.

 

export const GET = async () => {
  return NextResponse.json({ message: 'Hello World!'}, { status: 200 });
}

 

I want to get the test state when I click the button. For eventHandle, create handler function:

const testGetHandler = async () => {
    const response = await fetch('/api', {
      method: 'GET',
    })
    
    if (response.status === 200) {
      const result = await response.json();
      setGetTestState(result.message);
    }
  }

 

Add button and p tag for presenting result.

<button onClick={testGetHandler} className="bg-gray-300 px-6 py-4 text-gray-900">Test Get button</button>
<p className="text-9xl">{getTestState}</p>

 

 

Cool. :D

 

I'm going to change the operation of GET function from simly delivering a test state to retrieving an image that I uploaded to my S3 bucket.

 

Updated GET function:

export const GET = async (req: NextRequest) => {
  const { searchParams } = new URL(req.url);
  const key = searchParams.get("key");
  
  if (!key) {
    return NextResponse.json({ error: "Missing 'key' parameter" }, { status: 400 });
  }
  
  const fileParams = {
    Bucket: Bucket,
    Key: key,
  }
  
  const s3Response = await s3.send(new GetObjectCommand(fileParams));
  
  const stream = s3Response.Body as ReadableStream;
  const headers = new Headers();
  headers.set("Content-Type", s3Response.ContentType || "application/octet-stream");
  
  return new Response(stream, { headers });
};

 

Handler function:

  const getImageHandler = async () => {
    const response = await fetch(`/api?key=Screenshot 2025-02-22 at 1.31.05 PM.png`);
    
    if (response.ok) {
      const blob = await response.blob();
      const url = URL.createObjectURL(blob);
      setImageSrc(url);
    }
  }

 

I directly put the name of image into api key parameter.

 

 

:D

 

 

Finally I'm going to add DELETE api.

export const DELETE = async (req: NextRequest) => {
  const { searchParams } = new URL(req.url);
  const key = searchParams.get("key");
  
  if (!key) {
    return NextResponse.json({ error: "Missing 'key' parameter" }, { status: 400 });
  }
  
  const fileParams = {
    Bucket: Bucket,
    Key: key,
  }
  
  await s3.send(new DeleteObjectCommand(fileParams))
  
  return NextResponse.json({ status: 200 });
}

 

Handler function:

const deleteHandler = async () => {
    const result = await fetch('/api?key=Screenshot 2025-02-22 at 1.31.05 PM.png', {
      method: 'DELETE',
    }).then((res) => res.json());
    
    if (result.status === 200) {
      alert('Successfully deleted the image');
    }
  }

 

 

1: click the delete image button.

 

2: check that the file has been removed from S3 storage.

 

 

All functions are working successfull!