86

I have a simple API function as below,

from fastapi import FastAPI

app = FastAPI()


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

I am starting the server using uvicorn command as,

uvicorn main:app

Since we are not calling any python file directly, it is not possible to call uvicorn command from Pycharm.

So, How can I run the fast-api server using Pycharm?

JPG
  • 82,442
  • 19
  • 127
  • 206

4 Answers4

180

Method-1: Run FastAPI by calling uvicorn.run(...)

In this case, your minimal code will be as follows,

# main.py

import uvicorn
from fastapi import FastAPI

app = FastAPI()


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


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

Normally, you'll start the server by running the following command,

python main.py

Pycharm Setup

For this setup, and now, you can set the script path in Pycharm's config

Pycharm-uvicorn.run

Notes

  • Script Path: path to the FastAPI script
  • Python Interpreter: Choose your interpreter/virtual environment
  • Working Directory: Your FastAPI project root

Method-2: Run FastAPI by calling uvicorn command

In this case, your minimal code will be as follows,

# main.py

from fastapi import FastAPI

app = FastAPI()


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

Normally, you'll start the server by running the following command,

uvicorn main:app --reload

Pycharm Setup

For this setup, and now, you can set the script path in Pycharm's config

Pycharm-uvicorn.command

Notes

  • Module name: set to uvicorn
  • [Optional] Script: Path to uvicorn binary. You will get the path by executing the command, which uvicorn , inside your environment. (See this image)
  • Parameters: The actual parameters of uvicorn command
  • Python Interpreter: Choose your interpreter/virtual environment
  • Working Directory: Your FastAPI project root
JPG
  • 82,442
  • 19
  • 127
  • 206
  • The problem is that you can't deploy to production this way because you can't really pass other parameters to uvicorn...say "workers", etc. At least I can't get it to work. – GregH Sep 22 '20 at 06:19
  • Also, this is *not for production*. Suppose if you want to update the number of workers, you need to update your code, which is of course not a good idea. That's why unicorn supports the commandline setup. – JPG Sep 22 '20 at 06:22
  • BTW, the `uvicorn.run(...)` supports all the args supported by the commandline – JPG Sep 22 '20 at 06:23
  • You can pass in args via pycharm and dynamically configure uvicorn all args supported via config = Config(app, **kwargs) – Timothy Mugayi Oct 12 '20 at 03:08
  • Could you explain why that matter here? Sorry that I didn't get your point @TimothyMugayi – JPG Oct 12 '20 at 03:14
  • I was looking for this solution for the past 2 (two) years now :) – Borko Rastović Jul 23 '21 at 06:57
  • Is running on `0.0.0.0` safe? I'm a novice but someone might have told me at some point, "don't do that". I changed it to `localhost` and it works. – mLstudent33 Sep 06 '21 at 01:45
43

You can do it without adding code to main.py

  1. In target to run instead of Script path choose Module name
  2. In Module name type uvicorn
  3. In parameters app.main:app --reload --port 5000

enter image description here

Rui Peres
  • 25,741
  • 9
  • 87
  • 137
Max
  • 1,634
  • 1
  • 19
  • 36
12

Try to call uvicorn inside your code. e.g:

from fastapi import FastAPI
import uvicorn

app = FastAPI()


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

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=5000, log_level="info")

Reference

Nicolas Acosta
  • 742
  • 5
  • 12
3

Another example, this might be helpful to someone.

# fastapi_demo.py

import uvicorn
from fastapi import FastAPI, Response

app = FastAPI()

@app.route('/', methods=['POST'])
def demo(request):
    try:
        print(request)
    except Exception as e:
        print(e)
    return Response(content='OK')


if __name__ == '__main__':
    uvicorn.run(app='fastapi_demo:app')
Suyog Shimpi
  • 706
  • 1
  • 8
  • 16
  • this results in the fastapi_demo to be run twice. If you have a (for example) global variable it will be initialized – jaecktec Sep 19 '21 at 09:19
  • Thanks, @Coco to identify my mistake. It was running twice just because of misconfiguration. Actually, I have added `reload=True` and it leads to double initialization. To avaid that you must add `reload_dirs=['/app_dir_name',]`. But, this approach is not wrong to run app by PyCharm. [Check this](https://www.uvicorn.org/#running-programmatically) FYI – Suyog Shimpi Sep 20 '21 at 06:43
  • you would need to run `uvicorn.run(app)` instead, that'd not start the app twice – jaecktec Oct 24 '21 at 19:37