Reputation: 88619
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?
Upvotes: 103
Views: 108483
Reputation: 1
Firstly, setup your python conda env / venv in Pycharm Project Settings. And add configuration as shown in below image:
This works for me.
Upvotes: 0
Reputation: 6442
PyCharm Professional now lets you select FastAPI as your project type. Even if you didn't start that way, there is an associated FastAPI run config template that you can use on other projects. Example config for debugging FastAPI running in a Docker container:
Upvotes: 2
Reputation: 1844
You can do it without adding code to main.py
target to run
instead of Script path
choose Module name
Module name
type uvicorn
app.main:app --reload --port 5000
Upvotes: 58
Reputation: 866
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')
Upvotes: 6
Reputation: 88619
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
For this setup, and now, you can set the script path in Pycharm's config
uvicorn
commandIn 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
For this setup, and now, you can set the script path in Pycharm's config
uvicorn
uvicorn
binary. You will get the path by executing the command, which uvicorn
, inside your environment. (See this image)uvicorn
commandUpvotes: 219
Reputation: 807
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")
Upvotes: 14