Step-by-Step Guide to Creating a FastAPI Project in PyCharm
Ravi Teja Step-by-Step Guide to Creating a FastAPI Project in PyCharm

Step-by-Step Guide to Creating a FastAPI Project in PyCharm

Introduction FastAPI is a modern, high-performance web framework for building APIs with Python. If you're using PyCharm as your IDE, setting up a FastAPI project is straightforward. In this guide, we will walk through the process of creating a FastAPI project in PyCharm from scratch.


Step 1: Install PyCharm

If you haven't installed PyCharm yet, download and install it from the official JetBrains website: PyCharm Download.

Once installed, open PyCharm and create a new project.


Step 2: Create a New Project

  1. Open PyCharm and click on Create New Project.
  2. Select Virtualenv as the environment.
  3. Choose the Python interpreter (Python 3.7+ is recommended for FastAPI).
  4. Set a project location and click Create.


Step 3: Install FastAPI and Uvicorn

After setting up the project:

  • Open the Terminal in PyCharm.
  • Run the following command to install FastAPI and Uvicorn (the ASGI server for running FastAPI applications):

pip install fastapi uvicorn        

  • Verify the installation by running:

python -c "import fastapi; print(fastapi.__version__)"        

Step 4: Create the Main FastAPI Application File

  1. Inside your project directory, create a new Python file, e.g., main.py.
  2. Add the following FastAPI boilerplate code:

from fastapi import FastAPI

app = FastAPI()

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

Step 5: Run the FastAPI Application

  • In the terminal, run the following command to start the application:

uvicorn main:app --reload        

  • You should see output indicating that Uvicorn is running.
  • Open a web browser and visit: https://127.0.0.1:8000.
  • To explore the auto-generated API documentation, go to:
  • Swagger UI: https://127.0.0.1:8000/docs
  • Redoc UI: https://127.0.0.1:8000/redoc


Step 6: Configuring PyCharm for FastAPI Development

Enable Virtual Environment

  • Open File > Settings > Project: > Python Interpreter.
  • Ensure the correct virtual environment is selected.

Run Configurations

  • Go to Run > Edit Configurations.
  • Click + (Add New Configuration) and select Python.
  • Set the script path to uvicorn and parameters as:

main:app --host 127.0.0.1 --port 8000 --reload        

  • Save and run the configuration.


Step 7: Creating API Endpoints

Extend your FastAPI application by adding more endpoints:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def home():
    return {"message": "Welcome to FastAPI"}

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

要查看或添加评论,请登录

Ravi Teja的更多文章

其他会员也浏览了