Hello World In Fast API Python

In this blog, we will guide you on creating a simple "Hello World" API using FastAPI. FastAPI is a modern and fast web framework for building APIs with Python 3.6+ based on the popular and powerful ASGI framework, Starlette. It is designed to be easy to use and understand, focusing on developer productivity and code clarity.

Prerequisites

Before we get started, ensure that you have the following:

  • Python 3.6 or above
  • pip
  • FastAPI and Uvicorn (installed via pip)

Step 1: Create a New Project

The first step is to create a new project directory for your FastAPI project. Open your terminal or command prompt and create a new directory,

mkdir fastapi-hello-world

Navigate into the directory using,

cd fastapi-hello-world

Step 2: Create a New Python File

Create a new Python file using the touch command,

touch main.py

Open the file using your preferred text editor and paste in the following code,

from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"}

In the above code, we imported the FastAPI class and created an instance of it. We then defined a route with the @app.get decorator. This route will be accessible at the root URL ("/"). When a user visits this route, the read_root function will be called, which returns a JSON object with a simple "Hello World" message.

Step 3: Run the Application

To run the application, we need to use an ASGI server. Uvicorn is a fast ASGI server that can be used to run FastAPI applications. To install Uvicorn, run the following command,

pip install uvicorn

Once Uvicorn is installed, we can start our FastAPI application by running the following command,

uvicorn main:app --reload

The main:app argument specifies that we want to run the app instance we created in the main.py file. The --reload argument tells Uvicorn to automatically reload the server when changes are made to the code.

Once the server is running, you should see output similar to the following,

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

You can now visit http://127.0.0.1:8000 in your web browser to see the "Hello World" message.

Congratulations! You have created a "Hello World" API using FastAPI.

Conclusion

FastAPI is a powerful and easy-to-use web framework for building APIs with Python. In this blog post, we walked you through the process of creating a simple "Hello World" API using FastAPI. With FastAPI, you can create robust and scalable APIs