TutorialsAPI Call

API Calls

Creating an API

Creating new APIs in ShipAny follows the same rules as creating new APIs in the NextJS framework.

  1. Create an API folder under the app/api directory and create a new route.ts file

  2. Implement the API business logic

app/api/ping/route.ts
import { respData, respErr } from "@/lib/resp";
 
export async function POST(req: Request) {
  try {
    const { message } = await req.json();
    if (!message) {
      return respErr("invalid params");
    }
 
    return respData({
      pong: `received message: ${message}`,
    });
  } catch (e) {
    console.log("test failed:", e);
    return respErr("test failed");
  }
}

Debugging the API

  1. Debug the API using the curl command in terminal
Terminal
curl -X POST -H "Content-Type: application/json" \
    -d '{"message": "hello"}' \
    http://localhost:3000/api/ping
  1. Or debug the API using VS Code’s REST Client plugin

ping-api

References