Step-by-Step Tutorial: Building a NextJS + FastAPI Application

Posted by


Building a NextJS + FastAPI application can be a great way to create a powerful web application with a powerful frontend and backend framework. In this tutorial, we will go through the steps of building a NextJS application for the frontend and integrating it with a FastAPI backend.

Step 1: Setting up the FastAPI backend

  1. Install FastAPI and Uvicorn: First, we need to install FastAPI and Uvicorn, which is a lightning-fast ASGI server.
pip install fastapi uvicorn
  1. Create a new directory for your FastAPI project and navigate to it:
mkdir fastapi-backend
cd fastapi-backend
  1. Create a new Python file for your FastAPI app, for example, main.py, and import the necessary modules:
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}
  1. Start the FastAPI server using Uvicorn:
uvicorn main:app --reload

Now, you should see the FastAPI server running at http://127.0.0.1:8000.

Step 2: Setting up the NextJS frontend

  1. Create a new directory for your NextJS project and navigate to it:
npx create-next-app nextjs-frontend
cd nextjs-frontend
  1. Create a new page in the pages directory, for example, index.js, and add some content:
export default function Home() {
  return <h1>Hello, NextJS + FastAPI!</h1>;
}
  1. Start the NextJS development server:
npm run dev

Now, you should see your NextJS app running at http://localhost:3000.

Step 3: Integrating the NextJS frontend with the FastAPI backend

  1. Create an API route in your FastAPI backend to serve data to your NextJS frontend. Modify your main.py file to include an API route:
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}

@app.get("/api/data")
async def get_data():
    return {"data": "This is some data from the backend!"}
  1. Update your NextJS frontend to fetch data from the API route. Modify your index.js file to include an API call using fetch:
export default function Home({ data }) {
  return <h1>{data}</h1>;
}

export async function getStaticProps() {
  const res = await fetch('http://localhost:8000/api/data');
  const { data } = await res.json();

  return { props: { data } };
}
  1. Restart both the FastAPI and NextJS servers, and you should see your NextJS app displaying data fetched from the FastAPI backend.

Congratulations! You have successfully built a NextJS + FastAPI application. This tutorial covers the basics of setting up the frontend and backend, integrating them, and fetching data from the backend in your frontend. Feel free to explore and expand on this foundation to build more complex and feature-rich applications.

0 0 votes
Article Rating
17 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@evrenyilmazz
2 months ago

Thank you very much 🙂

@guybrushthreepwood2567
2 months ago

Very nice tutorial, but as someone who watches a lot of tutorials – please consider speeding up the "typing part" of your tutorials. It's obvious that most instructors are just reading and re-typing or copy-pasting blocks of code from the other screen, and there's nothing wrong with that. But typing doesn't make it any more "organic", it's flawless and perfect (down to imports on the top of the file before you even start writing your code, which is obviously how all of us real developers don't actually write code, you import/include stuff as you need it, not randomly from top of our minds). So to make it more fun – just copy blocks of code, entire function at a time, and then instead of making us watch how you "retype" the function – spend that time explaining what the method does, what the arguments are, why you prefer doing it this way or another, but then it's time well spent. Watching someone slowly retype the entire app is.. not high value. But other than that – great video, I love your style and I think your channel will only grow from here! Keep up the good work dude! 🤙

@iekmasolutions
2 months ago

Please make a full video on realtime chap app with notification and websocket and mysql

@stylinali
2 months ago

Please make more projects, and thanks for it.

@coff3andprograming
2 months ago

It could have been better if they had implemented pandas and uploaded csv, excel or txt files

@PukhtoonPeGermanyKe
2 months ago

❤Amazing

@viniciusm.m.7822
2 months ago

Thanks!
Abraço do Brasil!

@agungliem1219
2 months ago

Hi Eric, i have problem with ModuleNotFoundError: No module named 'jose'.
Please help me.

@muhammadfawwad6782
2 months ago

make an ecommerce website with fast api

@user-ju5zm4vw1n
2 months ago

Wow beautiful, I'm currently working on a fastapi and nextjs project and you just save me a lot of time, thanks for such an amazing tutorial.

@zeecomedia
2 months ago

Awesome Roby ❤, i super love this full stack tutorial. I would be working on such in my channel too 🥰

@tryingtobebetterr
2 months ago

A comment advising you to show a demo at the beginning of the video is a golden one. I would say add timestamps to your videos. Good work, regardless.

@efbYouTube
2 months ago

Thanks!

@francosbenitez
2 months ago

Clear and straight to the point. Great content!

@user-xd6fr3hs2z
2 months ago

Although your tutorial is helpful, why aren't you using SQLModel as the ORM and Poetry for dependency management?

@django1000
2 months ago

Nice tutorial.
Try to show demo site in the beginning so viewers can see what's they are gonna learn.

Keep up the good work 🎉❤

@berthembenitezjr8612
2 months ago

Wow is this free? No paid stuff for fullstack dev.