How to create an Blog post api in NextJs

Here we will learn how to create an api in NextJs 14.2.0

How to create an API in NextJs 14

# First create NextJs app

npm init
npm create nextapp@latest

# Now create api folder under the app folder

# New create a folder and route.tsx file within this folder


Import module

import { MONGO_URI } from "@/lib/db";
import { Blog } from "@/lib/model/blogModel";
import { HttpStatusCode } from "axios";
import { error } from "console";
import mongoose from "mongoose";
import { NextApiRequest, NextApiResponse } from "next";
import { NextRequest, NextResponse } from "next/server";


# Define body structure

interface RequestBody {
    title: string;
    description: string;
    content:string;
}


# Now create validation function

function validateRequest(object: any): object is RequestBody {
    return (
        (object as RequestBody) && typeof (object as RequestBody).title === "string" && (object as RequestBody).title.length >=6
    );
}


# Now create GET function to fetch the data from the database

export const GET = async (req: { nextUrl: { searchParams: any; }; }) => {


    try {


        await mongoose.connect(MONGO_URI);


        const data = await Blog.find();


        return NextResponse.json({ success: data })
    } catch (error) {
        return NextResponse.json({ error })
    }
}


# Now create POST function to upload the data on data base


export const GET = async (req: { nextUrl: { searchParams: any; }; }) => {


    try {

        await mongoose.connect(MONGO_URI);

        const data = await Blog.find();

        return NextResponse.json({ success: data })
    } catch (error) {
        return NextResponse.json({ error })
    }
}