Tutorial 2023: Creating Your First API with FastAPI in Python

Posted by


Creating your very first API with FastAPI in Python is a great way to get started with web development and building modern, efficient web applications. FastAPI is a fast (high-performance), easy to use, and flexible web framework for building APIs with Python. In this tutorial, we will go through the step-by-step process of creating your very first API with FastAPI in Python.

Before we get started, make sure you have Python installed on your computer. You can download and install Python from the official Python website. Once you have Python installed, you will also need to install FastAPI and Uvicorn, which is a lightning-fast ASGI server implementation, using pip, the package manager for Python. You can install FastAPI and Uvicorn by running the following commands in your terminal:

pip install fastapi
pip install uvicorn

Now that you have FastAPI and Uvicorn installed, let’s create our very first API with FastAPI in Python. First, create a new Python file called app.py. In this file, we will define our FastAPI application and create our API endpoints.

from fastapi import FastAPI

app = FastAPI()

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

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

In the code above, we first import the FastAPI class from the fastapi module, and then create a new instance of FastAPI called app. We then define two API endpoints using the @app.get decorator. The read_root function returns a simple JSON response with a message "Hello, World!", while the read_item function expects an item_id parameter and an optional q query parameter, and returns a JSON response with the values of these parameters.

Next, we need to run our FastAPI application using the Uvicorn server. To do this, open your terminal and run the following command:

uvicorn app:app --reload

This command tells Uvicorn to run the FastAPI application defined in the app.py file with automatic code reloading enabled. Once the server is running, you should see output similar to the following:

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [12345]
INFO:     Started server process [12346]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Now, open your web browser and navigate to http://127.0.0.1:8000/. You should see a JSON response with the message "Hello, World!". You can also try accessing different endpoints, such as http://127.0.0.1:8000/items/1 with or without a query parameter to test the read_item endpoint.

Congratulations! You have successfully created your very first API with FastAPI in Python. You can now build upon this example to create more complex APIs with FastAPI and explore its many features and capabilities. Happy coding!

0 0 votes
Article Rating

Leave a Reply

33 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@MarkBetterDev
20 days ago

Pretty much a flask app with Jason as return value.

@maxaaa9
20 days ago

cool video

@infohpreet
20 days ago

I like to fetch sql db data using fastapi endpoints

@infohpreet
20 days ago

Very nice way to show FastAPI for starters.

@kishanmunjapara5216
20 days ago

Super video, all in one ..👍👍👍👍👍

@PhucPham-my2qb
20 days ago

really straightforward many thanks

@locky916
20 days ago

thanks for the content I really enjoyed it and it was very good explanation for API concept. Thanks and keep working further.

@shotihoch
20 days ago

best kind of video you can find after phrase like "what the hell is _____" (in this case "fast api")

@user-gd8rd2hg9w
20 days ago

That's what is needed in short and elaborative way. Thanks mate

@Oof_the_gamer
20 days ago

I keep getting the error: Error loading ASGI app. Could not import module "main". , Can anyone help me?

@prior2915
20 days ago

I can't proceed I get an error that states "ERROR: Error loading ASGI app. Could not import module "main".

@pixdata8126
20 days ago

very clean explanation bro ❤❤❤❤

@waelitoz
20 days ago

Amazing. Clean, neat and well explained. Would be nice to see a gradual increase of complexity each of 10 min for other FastAPI videos.

@mishaed-pm3xx
20 days ago

I'd like to see a full tutorial on fastAPI 👍

@williamkakooza4603
20 days ago

Thanks alot

@rcjinAZ
20 days ago

Good explanation of FastAPI. Thumbs up.

@campbat5712
20 days ago

i always keep coming back because I forget the command to start uvicorn lol. for future me it's at 3:01

@skyagnitti
20 days ago

Best and most concise video I've found on FastAPI yet! I'm just getting started so thank you! I'm definitely going to watch your related videos and see if you made on on customizing the documentation..

@FDasdana
20 days ago

In this morning, I had to review the fastapi codes for the first time and the codes looked like black magic. I made a very simple and understandable start with this video.

Great content 👍

@TechySatvik
20 days ago

"Your FastAPI tutorial havs been a game-changer in my learning journey. Thanks for making it so much easier to grasp!" 😀😀😀😁😁😁

33
0
Would love your thoughts, please comment.x
()
x