Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 8563

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T02:19:08+00:00 2024-11-28T02:19:08+00:00

Re-Doing the Django Tutorial With FastAPI And React: Setting up a FastAPI project !

  • 60k

FastAPI is an awesome modern Python framework designed to enable developers to quickly build robust and performant APIs.
Once you start getting the hang of it, you can become super efficient in building new endpoints and implementing
complex business logic. However, it might be destabilizing at first when coming from more opiniated Framework like Django that
offers more functionnalities out of the box.

Thus, I thought it could be interesting (and fun !) to re-recreate the well known polls app from the Django tutorial, but this time using FastAPI
and React ! In this multi part series I'll try to follow the same path as the original as much as possible, although I'll probably split
some parts in two to avoid an overload of information.

Today is part 1 : Setting up the project, creating the polls app and making your first django view path operation

The code for this part is available here but I encourage you to code along instead !


🔧 Setting up the project

FastAPI is quite easy to setup, in fact all you need to run a FastAPI app is a singe file instantiating
the main app and an ASGI worker to run it. Of course we'll go a bit further. We'll run
the app in a Docker container so you'll need to have it installed on your machine

The docker image

First create a Dockerfile at the root of your working directory, and write the following instructions in it :

   FROM python:3.9  WORKDIR /app  # Install Poetry RUN curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | POETRY_HOME=/opt/poetry python &&      cd /usr/local/bin &&      ln -s /opt/poetry/bin/poetry &&      poetry config virtualenvs.create false   # Copy using poetry.lock* in case it doesn't exist yet COPY ./app/pyproject.toml ./app/poetry.lock* /app/  RUN poetry install --no-root --no-dev  COPY ./app /app   CMD ["uvicorn", "app.main:app", "--reload", "--host", "0.0.0.0", "--port", "80"]     
Enter fullscreen mode Exit fullscreen mode

This needs a bit of commenting.

The way dependencies are installed might seems a bit strange. Here we use poetry as a package manager, so we need to install it first and
then run install without creating a virtual env (that --no-root bit). What's great about this approach is that you can use
the same pyproject.toml in your developement environment so things like static analysis tools uses the same dependencies. In a production
settings we would probably creat a multi-stage build and discard poetry to have a slimer image.

The app folder will be created in the next section that's where our code will live.

Finally, notice the --reload option we pass to uvicorn which will allows us to work without having to restart the worker everytime we make
a change.

We'll launch the container a bit later, first we need to initialize the app !

The fastapi app

First things first, let's create the folder where our code will live: mkidr app

Now as I said we'd only need to create a main.py file if we wanted to. But to stay true to the theme of this serie, I'd like
to create a directory structure similar to django apps. That's why we'll create a second app directory that will be our “main”
app. Later we'll also create a polls directory.

For now simply run mkdir app/app to create the folder, and create a main.py file inside of it. Your directory strucutre should now
look like this :

directory structure

Perfect ! And now buckle up as the obligatory hello world ! is approaching. Inside main.py write the following lines :

   from fastapi import FastAPI   app = FastAPI()   @app.get("/") async def root():     return {"message": "Hello World"}    
Enter fullscreen mode Exit fullscreen mode

This will initialize the app and create our first path operation. This one
is straight from the docs ! But you can't see the message yet as we still need to launch the container. We're almost there,
head over to the next section !

Launching the app

Before launching the app we need to build the image first. From the root of your project run docker build -t poll-app .

Now we can launch the container: docker run -it -p 80:80 -v "$(pwd)"/app:/app poll-app. This will also mount
our app directory so we don't have to recreate it each time we edit the files.

We're now ready to test our endpoint. In your browser navigate to localhost and behold !

![Hello World](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t15xesaslo9r7u77akgt.png)
![Hello world](https://media.giphy.com/media/lIzAEoZEn571u/giphy.gif) *… general kenobi*

Now that's already good, but what is great is that FastAPI comes with a built in and Swagger for which the open api configuration
is autogeneated. That means that if you go to localhost/docs you'll see the following :

docs

FastAPI automatically generate your endpoint documentation ! Pretty neat feature for an API to have if you ask me.


📜 Creating a poll app

Now that Hello world ! is out of the way (I recommend adding it to your personnal collection), let's get to the actual polls app. As
I mentionned earlier we'll create a polls directory along side the main app. Once that's done add a file called endpoints.py to
this new folder, your project' structure should look like that :

Directory Structure

Don't forget to create the relevant __init__.py file so the folder are recognized as Python modules

Now let's create an index for our polls app. This index will later be responsible for listing the available polls in our database but for now it will return a simple message. Add the following code to the polls/endpoints.py:

     from fastapi import APIRouter    router = APIRouter()     @router.get("/")   async def index():       return {"message": "polls index"}     
Enter fullscreen mode Exit fullscreen mode

Here we use APIrouter to declare our path operations. It works exatcly the same as
the FastaAPI(). Now all we need to do to make our endpoint available, is to declare it in main.py:

   app.include_router(polls.endpoints.router, prefix="/polls")    
Enter fullscreen mode Exit fullscreen mode

The prefix indidates that all the routes coming from the polls endpoints start with polls. Your polls index should now be available both
at localhost/polls and in the Swagger documentation ! Let's take a look !

swagger polls

Great ! Our polls index works, although it doesn't return anything yet, we'll chnage that in part 2!


Conclusion

That's is for part 1, let me know if you found it useful ! In part 2, we'll see how to set up an actual database to store our polls !

fastapipythontutorialwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.