Virtual Environment and FastAPI Setup
00:00 Before creating a REST API with FastAPI, it’s a good idea to create a new Python virtual environment. I’m in Visual Studio Code on Windows, but you can follow along on macOS or even Linux, or you can use your own editor, but Visual Studio Code has great Python support.
-m option invokes a module named
venv that will create a new virtual environment in a directory called
.env, but you can name it whatever you like. After the virtual environment is finished, open the project directory in Visual Studio, and this can be done by executing this command.
01:18 The Python extension provides support for virtual environments with the Python: Select Interpreter command. This will look for Python virtual environments—including those created by Conda, pipenv, and Poetry—and prompt you to select one.
02:17 Notice that you’re returning a dictionary, but recall in the last lesson that data returned from a REST API is usually JSON. If you’ve worked with the JSON module in the Python standard library, you know that marshaling data between Python dictionaries and JSON objects is a cinch.
The two are almost syntactically identical. FastAPI will translate this data from a dictionary to JSON for you and return it in an HTTP response with the appropriate status code,
200 for OK in this case.
To map the function to an endpoint, use the
@get decorator from the FastAPI app, The
@get decorator accepts a path. Now, any request using the
.get() method or verb to the root of the API will be handled by the
03:39 For example, the package for Flask implements a WSGI server you could use to run Flask applications. ASGI is Async Server Gateway Interface, and you can install the uvicorn package and use it to serve your API.
To use uvicorn to serve your API, you can import it into
main.py and invoke the server in the entry point. This would be the only choice if you were using something like Replit to develop your API. However, it’s easier to run it from the command line.
If you navigate to
http://localhost:8000 in a browser, you’ll see the JSON returned by the
root() function. Congratulations! You’ve created your first REST API using FastAPI. In the next lesson, you’ll learn how to use FastAPI’s interactive documentation.
Become a Member to join the conversation.