Skip to main content

Add a New API

ShipNowKit uses Next.js Route Handlers to create API endpoints. Let's learn how to add new API routes with TypeScript support and proper error handling.

Creating a Basic API Route

To create a new API endpoint, follow these steps:

  1. Create a new folder in the app/api directory (e.g., users)
  2. Add a route.ts file inside this folder
  3. Implement the API handler

Here's a simple example:

app/api/users/route.ts
import { NextResponse } from 'next/server';

export async function GET() {
return NextResponse.json({
users: [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' }
]
});
}

This creates an API endpoint accessible at /api/users that returns a list of users.

You can test your API endpoints using tools like Postman or curl. Below is an example of how to test the API endpoint via Postman: image.png

Handling Different HTTP Methods

A complete API endpoint often needs to handle multiple HTTP methods. Here's an example showing how to implement CRUD operations:

app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';


// GET /api/users
export async function GET() {
return NextResponse.json({
users: [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' }
]
});
}

// POST /api/users
export async function POST(request: NextRequest) {
const body = await request.json();
if (!body.name) {
return NextResponse.json(
{ error: 'Name is required' },
{ status: 400 }
);
}

const newUser = {
id: Date.now(),
name: body.name,
};

return NextResponse.json(newUser, { status: 201 });
}

Dynamic Routes

For handling dynamic routes (e.g., getting a specific user by ID), create a new folder with parameter notation:

app/api/users/[id]/route.ts
import { NextRequest, NextResponse } from 'next/server';

interface RouteParams {
params: {
id: string;
};
}

export async function GET(request: NextRequest, { params }: RouteParams) {
const userId = params.id;
const user = {
id: parseInt(userId),
name: 'John Doe',
email: '[email protected]',
role: 'user'
};
return NextResponse.json(user, { status: 200 });
}

Best Practices

  1. Input Validation: Always validate request data
  2. Error Handling: Use try-catch blocks and return appropriate status codes
  3. Type Safety: Define interfaces for request/response data
  4. Authentication: Implement proper authentication for protected routes
  5. Response Format: Maintain consistent response structure
  6. Status Codes: Use appropriate HTTP status codes
  7. Rate Limiting: Implement rate limiting for production APIs

Further Resources