Example GET, POST, PATCH, DELETE for app/api/name/route.js
Unanswered
Bohemian Waxwing posted this in #help-forum
Bohemian WaxwingOP
I tried to find example using Google and even in AI, but can't find a good one without an error.
Does anyone have an example please?
Does anyone have an example please?
20 Replies
Pteromalid wasp
You mean something like this?
import { NextRequest, NextResponse } from "next/server";
/**
* Details.
* @param {NextRequest} request - The incoming request object.
* @returns {Promise<NextResponse>} The response object.
*/
export async function GET(request: NextRequest): Promise<NextResponse> {
// Logic
return NextResponse.json(
{ message: "API is working!." },
{ status: 200}
);
}You can change GET for POST, PUT, etc
If you want to get you POST data you can type:
try {
// Parse the request body
const reqBody = await request.json();
const { email, password, rememberMe } = reqBody;
....
}@Pteromalid wasp If you want to get you POST data you can type:
TS
try {
// Parse the request body
const reqBody = await request.json();
const { email, password, rememberMe } = reqBody;
....
}
Bohemian WaxwingOP
Nice!!!!! I missing this part. I'll post a 'template' for those who try to do the same as me for their reference.
Thanks @Pteromalid wasp
Thanks @Pteromalid wasp
Bohemian WaxwingOP
For those who want a template
----
export async function GET(request) {
try {
const data = await collection.find({}).sort({ _id: -1 }).toArray();
return NextResponse.json(data);
} catch (e) {
console.error(e);
}
}
export async function POST(request) {
try {
// Parse the request body
const reqBody = await request.json();
const { PremiseName } = reqBody;
const { PremiseAddress } = reqBody;
const { PremiseCountry } = reqBody;
const { PremiseLat } = reqBody;
const { PremiseLon } = reqBody;
const { PremisePhone } = reqBody;
const { PremiseEmail } = reqBody;
const { PremisePackage } = reqBody;
const Status = 'PENDING';
const bodyObject = {
PremiseName: PremiseName,
PremiseAddress: PremiseAddress,
PremiseCountry: PremiseCountry,
PremiseLat: PremiseLat,
PremiseLon: PremiseLon,
PremisePhone: PremisePhone,
PremiseEmail: PremiseEmail,
PremisePackage: PremisePackage,
PremiseStatus: Status,
CreatedOn: new isoDate(new Date()),
};
try {
const data = await collection.insertOne(bodyObject);
return NextResponse.json(data, { message: 'success' }, { status: 200 });
} catch (e) {
console.error(e);
}
} catch (err) {
// If there was an error parsing the request body, return an error response
return NextResponse.json({ message: 'Invalid request body' }, { status: 400 });
}
}
-----
Hopefully NextJS documentation do have details for this.
----
export async function GET(request) {
try {
const data = await collection.find({}).sort({ _id: -1 }).toArray();
return NextResponse.json(data);
} catch (e) {
console.error(e);
}
}
export async function POST(request) {
try {
// Parse the request body
const reqBody = await request.json();
const { PremiseName } = reqBody;
const { PremiseAddress } = reqBody;
const { PremiseCountry } = reqBody;
const { PremiseLat } = reqBody;
const { PremiseLon } = reqBody;
const { PremisePhone } = reqBody;
const { PremiseEmail } = reqBody;
const { PremisePackage } = reqBody;
const Status = 'PENDING';
const bodyObject = {
PremiseName: PremiseName,
PremiseAddress: PremiseAddress,
PremiseCountry: PremiseCountry,
PremiseLat: PremiseLat,
PremiseLon: PremiseLon,
PremisePhone: PremisePhone,
PremiseEmail: PremiseEmail,
PremisePackage: PremisePackage,
PremiseStatus: Status,
CreatedOn: new isoDate(new Date()),
};
try {
const data = await collection.insertOne(bodyObject);
return NextResponse.json(data, { message: 'success' }, { status: 200 });
} catch (e) {
console.error(e);
}
} catch (err) {
// If there was an error parsing the request body, return an error response
return NextResponse.json({ message: 'Invalid request body' }, { status: 400 });
}
}
-----
Hopefully NextJS documentation do have details for this.
Bohemian WaxwingOP
@Pteromalid wasp , how about get?
Example my get url /api/premises?hid=abc
I can see in request
----
NextRequest [Request] {
[Symbol(internal request)]: {
cookies: RequestCookies { _parsed: [Map], _headers: [HeadersList] },
geo: {},
ip: undefined,
nextUrl: NextURL { [Symbol(NextURLInternal)]: [Object] },
url: 'http://localhost:3000/api/premises?hid=7b40a366-c97b-46b8-af16-7032ef6e901b'
}
}
Example my get url /api/premises?hid=abc
I can see in request
----
NextRequest [Request] {
[Symbol(internal request)]: {
cookies: RequestCookies { _parsed: [Map], _headers: [HeadersList] },
geo: {},
ip: undefined,
nextUrl: NextURL { [Symbol(NextURLInternal)]: [Object] },
url: 'http://localhost:3000/api/premises?hid=7b40a366-c97b-46b8-af16-7032ef6e901b'
}
}
@Bohemian Waxwing <@1255904721571676185> , how about get?
Example my get url /api/premises?hid=abc
I can see in request
----
NextRequest [Request] {
[Symbol(internal request)]: {
cookies: RequestCookies { _parsed: [Map], _headers: [HeadersList] },
geo: {},
ip: undefined,
nextUrl: NextURL { [Symbol(NextURLInternal)]: [Object] },
url: 'http://localhost:3000/api/premises?hid=7b40a366-c97b-46b8-af16-7032ef6e901b'
}
}
Pteromalid wasp
What's your code currently and what are you trying to achieve
@Pteromalid wasp What's your code currently and what are you trying to achieve
Bohemian WaxwingOP
api location in /app/api. This to make sure it can only be use internal only. I can see it is different with /pages/api.
So i pass GET url /api/premise?hid=abc
Then the api will search for abc hid in database. In another word, I want to extract the hid from the url
So i pass GET url /api/premise?hid=abc
Then the api will search for abc hid in database. In another word, I want to extract the hid from the url
Bohemian WaxwingOP
or I should use /app/api/premises/[id]
Bohemian WaxwingOP
Nevermind. Found the solution
export async function GET(request) {
const { searchParams } = new URL(request.url);
const hid = searchParams.get('hid');
const id = searchParams.get('id');
if (hid) {
try {
console.log('get hid: ' + hid);
const data = await collection.find({ PremiseVendorHID: hid }).sort({ _id: 1 }).toArray();
return NextResponse.json(data);
} catch (e) {
console.error(e);
}
} else if (id) {
try {
const data = await collection.find({ _id: new ObjectId(id) }).toArray();
return NextResponse.json(data);
} catch (e) {
console.error(e);
}
} else {
try {
const data = await collection.find({}).sort({ PremiseName: 1 }).toArray();
return NextResponse.json(data);
} catch (e) {
console.error(e);
}
}
}
export async function GET(request) {
const { searchParams } = new URL(request.url);
const hid = searchParams.get('hid');
const id = searchParams.get('id');
if (hid) {
try {
console.log('get hid: ' + hid);
const data = await collection.find({ PremiseVendorHID: hid }).sort({ _id: 1 }).toArray();
return NextResponse.json(data);
} catch (e) {
console.error(e);
}
} else if (id) {
try {
const data = await collection.find({ _id: new ObjectId(id) }).toArray();
return NextResponse.json(data);
} catch (e) {
console.error(e);
}
} else {
try {
const data = await collection.find({}).sort({ PremiseName: 1 }).toArray();
return NextResponse.json(data);
} catch (e) {
console.error(e);
}
}
}
Thanks
@Bohemian Waxwing or I should use /app/api/premises/[id]
Pteromalid wasp
I dont suggest that, just use params like you did here:
/api/premise?hid=abc@Pteromalid wasp I dont suggest that, just use params like you did here: `/api/premise?hid=abc`
Bohemian WaxwingOP
noted
@Bohemian Waxwing Nevermind. Found the solution
export async function GET(request) {
const { searchParams } = new URL(request.url);
const hid = searchParams.get('hid');
const id = searchParams.get('id');
if (hid) {
try {
console.log('get hid: ' + hid);
const data = await collection.find({ PremiseVendorHID: hid }).sort({ _id: 1 }).toArray();
return NextResponse.json(data);
} catch (e) {
console.error(e);
}
} else if (id) {
try {
const data = await collection.find({ _id: new ObjectId(id) }).toArray();
return NextResponse.json(data);
} catch (e) {
console.error(e);
}
} else {
try {
const data = await collection.find({}).sort({ PremiseName: 1 }).toArray();
return NextResponse.json(data);
} catch (e) {
console.error(e);
}
}
}
Pteromalid wasp
Why not use NextJS's built in functions? Like:
[if link is:
UPDATE: nevermind, didn't see it was an API route, useSearchParams is for client components only
[if link is:
/api/premise?hid=abc]import { useSearchParams } from "next/navigation";
...
const [searchParams, setSearchParams] = useSearchParams();
const search = searchParams.get('hid');
...UPDATE: nevermind, didn't see it was an API route, useSearchParams is for client components only
Pteromalid wasp
What you have is fine 🙂
Bohemian WaxwingOP
I don't want to complex the API by validate JWT during send or request to public API for a security
However I wonder, will API route works with PWA.