FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. It is built on top of Starlette for the web parts and Pydantic for the data parts.

In this post, we'll go over the basics of initializing a FastAPI app and setting it up to handle requests.

Installation

To start using FastAPI, you'll need to have Python 3.6+ and pip (the package installer for Python) installed on your computer. You can check your version of Python by running the following command in your terminal:

python --version

Once you have Python and pip set up, you can install FastAPI by running the following command:

pip install fastapi

Creating a new FastAPI app

To create a new FastAPI app, you'll need to import FastAPI from the fastapi module and instantiate it. Here's an example of how to do that:

from fastapi import FastAPI

app = FastAPI()

This will create a new FastAPI app instance, which you can then use to define your API endpoints.

Defining endpoints

FastAPI uses the decorator pattern to define endpoints. Here's an example of a simple endpoint that responds to a GET request with a JSON object:

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

In this example, the @app.get("/") decorator tells FastAPI that this function should handle GET requests to the root path. The async def keyword is used to define an asynchronous function.

You can also define endpoints that take parameters, like this:

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

In this example, the {item_id} in the path is a path parameter, and the item_id: int in the function signature is a type hint that tells FastAPI to expect an integer value for that parameter.

Running the app

To run your FastAPI app, you'll need to use the run method on the app object. Here's an example of how to do that:

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

This will start the web server on IP address 0.0.0.0 and port 8000, which means it will be available on any IP address on port 8000 of the host machine.

Conclusion

In this post, we've covered the basics of initializing a FastAPI app and setting it up to handle requests. We've also gone over how to define endpoints and how to run the app. With this information, you're now ready to start building your own APIs with FastAPI!

Getting Started with FastAPI: Initializing Your App