Introduction: What is FastAPI and Why Use It?
Lesson 12: Install FastAPI and Create Your First Endpoint
Welcome to the most exciting lesson so far! In the previous lessons, you learned Python basics, how to handle files, manage packages, and even understood what HTTP and REST APIs are. Now it's time to put that knowledge into action. In this lesson, you will install FastAPI, run your first web server, and create your very first API endpoint. By the end, you will have a working API that responds to your browser.
What is FastAPI?
FastAPI is a modern, fast (high-performance) web framework for building APIs with Python. It is designed to be easy to use, highly productive, and automatically generates interactive documentation. Think of it as a set of tools that lets you turn your Python functions into web endpoints that can be called over the internet.
Why Do We Need It?
Without a framework like FastAPI, you would have to manually handle HTTP requests, parse JSON, manage routing, and deal with many low-level details. FastAPI does all of this for you, so you can focus on writing the logic of your application. It also validates data automatically and provides a beautiful Swagger UI for testing your API.
Step 1: Install FastAPI and Uvicorn
Before we start, make sure you have Python installed (version 3.7 or higher). Open your terminal or command prompt and run the following commands:
pip install fastapi
pip install uvicorn
What is Uvicorn? Uvicorn is an ASGI server that runs your FastAPI application. It listens for incoming HTTP requests and sends them to your FastAPI app.
Step 2: Create Your First FastAPI Application
Create a new file called main.py in a folder of your choice. Open it in your code editor and write the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, World!"}
Explanation:
from fastapi import FastAPI– imports the FastAPI class.app = FastAPI()– creates an instance of the FastAPI application.@app.get("/")– a decorator that tells FastAPI that the function below should handle GET requests to the root path ("/").def read_root():– the function that runs when someone visits the root URL.return {"message": "Hello, World!"}– returns a JSON response. FastAPI automatically converts the Python dictionary to JSON.
Step 3: Run Your API
In your terminal, navigate to the folder containing main.py and run:
uvicorn main:app --reload
Explanation of the command:
main– the name of your Python file (without .py).app– the name of the FastAPI instance inside that file.--reload– makes the server automatically restart whenever you change the code. This is very useful during development.
You should see output like:
INFO: Uvicorn running on http://127.0.0.1:8000
INFO: Application startup complete.
Step 4: Test Your First Endpoint
Open your web browser and go to http://127.0.0.1:8000. You should see the JSON response:
{"message": "Hello, World!"}
Congratulations! You have just created and run your first API endpoint.
Step 5: Explore the Automatic Documentation
FastAPI automatically generates interactive API documentation. Visit the following URLs in your browser:
- Swagger UI:
http://127.0.0.1:8000/docs - ReDoc:
http://127.0.0.1:8000/redoc
These pages show all your endpoints, allow you to test them directly from the browser, and display the expected request and response formats.
Practical Code Example: Adding a Second Endpoint
Let's add another endpoint that returns a custom greeting. Update your main.py file:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, World!"}
@app.get("/greet/{name}")
def greet_user(name: str):
return {"greeting": f"Hello, {name}!"}
What's new?
@app.get("/greet/{name}")– defines a path parameter{name}. When you visit/greet/John, the value "John" is passed to the function.name: str– tells FastAPI that the parameter should be a string. FastAPI will automatically validate this.return {"greeting": f"Hello, {name}!"}– uses an f-string to create a personalized message.
Save the file. The server will reload automatically. Now visit http://127.0.0.1:8000/greet/Ahmed in your browser. You should see:
{"greeting": "Hello, Ahmed!"}
Common Mistakes and How to Avoid Them
- Forgetting to install Uvicorn: If you get a "command not found" error, make sure you installed Uvicorn with
pip install uvicorn. - Running the wrong file name: If you named your file
app.py, you must runuvicorn app:app --reload(the first part must match your file name). - Port already in use: If you see an error about the port being in use, you can change the port by running
uvicorn main:app --reload --port 8001. - Indentation errors: Python is sensitive to indentation. Make sure the function body is indented correctly (4 spaces).
Practice Task
Task: Create a new endpoint that returns information about a task. The endpoint should be at /task/{task_id} where task_id is an integer. It should return a dictionary with the task ID and a placeholder title. For example, visiting /task/1 should return {"task_id": 1, "title": "Sample Task"}.
Hint: Use task_id: int as the parameter and return a dictionary with the keys "task_id" and "title".
Summary
In this lesson, you learned how to install FastAPI and Uvicorn, create a basic FastAPI application, run it locally, and define your first endpoints. You also explored the automatic documentation and added a path parameter. This is the foundation for building more complex APIs in the upcoming lessons. Keep practicing and get ready for the next lesson where you will dive deeper into path and query parameters.

Loading ratings...