Skip to main content

Creating a FastAPI instance

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. It's easy to use and incredibly efficient. Today, we'll focus on creating a FastAPI instance.

Step 1: Install FastAPI and Uvicorn

Before we can create a FastAPI instance, we need to install FastAPI and Uvicorn (an ASGI server). You can do this by running the following command:

pip install fastapi uvicorn

Step 2: Import FastAPI

Next, we need to import FastAPI from the fastapi module. Add the following line to your Python script:

from fastapi import FastAPI

Step3: Create a FastAPI Instance

Now we're ready to create a FastAPI instance. We'll do this by assigning the FastAPI() class to a variable. This variable is usually called app. Here's how you do it:

app = FastAPI()

Step 4: Define Routes

With our FastAPI instance (app), we can now define routes. A route is a URL pattern that is used to find the appropriate resource on a web server. In FastAPI, we define a route using a decorator such as @app.get("/") that goes above a function. The function then gets executed when a user visits the specified route. Here's an example:

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

In this example, visiting the root URL ("/") of the website will return a JSON response containing {"Hello": "World"}.

Step 5: Run the Application

Now that we have a basic FastAPI application, we can run it using Uvicorn. Save your script (for example, as main.py), then run the following command in your terminal:

uvicorn main:app --reload

In this command, main is the name of your Python script (without the .py), and app is the name of your FastAPI instance.

You should now be able to navigate to http://localhost:8000 in your web browser and see the message {"Hello": "World"}.

Congratulations! You've created your first FastAPI instance.

Remember, this is just the beginning. FastAPI has many more features to explore, such as path parameters, query parameters, request bodies, data validation, authentication, and more. As you continue learning, you'll discover that FastAPI is not only fast and easy to use, but also powerful and flexible.


I hope this tutorial has helped you understand how to create a FastAPI instance. Happy coding!