FastAPI Python: Build A Simple API In Minutes
FastAPI has emerged as a modern, high-performance web framework for building APIs with Python. Its ease of use, speed, and automatic data validation make it a favorite among developers. This guide will walk you through creating a simple API using FastAPI, covering everything from setup to running your first endpoint.
Setting Up Your Environment
Before diving into the code, you'll need to set up your development environment. This involves installing Python (if you haven't already) and the FastAPI library.
Installing Python
If you don't have Python installed, download the latest version from the official Python website. Make sure to add Python to your system's PATH during the installation process so you can easily access it from the command line. You can verify the installation by opening your terminal or command prompt and typing python --version or python3 --version. This should display the version number of Python installed on your system.
Installing FastAPI and Uvicorn
FastAPI requires Uvicorn, an ASGI server, to run. You can install both using pip, the Python package installer. Open your terminal or command prompt and run the following command:
pip install fastapi uvicorn
This command installs FastAPI and Uvicorn, along with their dependencies. Once the installation is complete, you're ready to start building your API. Uvicorn is essential because it acts as the intermediary between your FastAPI application and the web server, handling incoming requests and managing the execution of your application. Without Uvicorn (or a similar ASGI server), FastAPI wouldn't be able to serve your API over the web. Think of Uvicorn as the engine that powers your FastAPI car, allowing it to drive and deliver responses to users.
Creating Your First FastAPI Application
Now that your environment is set up, let's create a simple FastAPI application. This will involve creating a Python file, importing FastAPI, and defining your first API endpoint.
Creating the main.py File
Create a new file named main.py. This file will contain the code for your FastAPI application. Open the file in your favorite code editor.
Importing FastAPI
At the top of your main.py file, import the FastAPI class from the fastapi library:
from fastapi import FastAPI
app = FastAPI()
This line imports the necessary class to create a FastAPI application and then instantiates it. The app variable will be used to define your API endpoints.
Defining Your First Endpoint
Let's define a simple endpoint that returns a greeting message. Add the following code to your main.py file:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello World"}
This code defines a GET endpoint at the root path ("/"). When a user accesses this endpoint, the read_root function will be executed, returning a JSON response with the message "Hello World". The @app.get("/") decorator tells FastAPI that this function should handle GET requests to the root path. The async keyword indicates that this is an asynchronous function, which is a key feature of FastAPI for handling requests concurrently and efficiently. Asynchronous functions don't block the execution of other tasks while waiting for I/O operations to complete, making your API more responsive and scalable. Essentially, it's like having multiple chefs in a kitchen who can work on different dishes simultaneously, rather than having one chef who has to complete each dish one at a time.
Running Your FastAPI Application
With your first endpoint defined, you can now run your FastAPI application. This involves using Uvicorn to serve your application.
Running Uvicorn
Open your terminal or command prompt, navigate to the directory containing your main.py file, and run the following command:
uvicorn main:app --reload
This command starts the Uvicorn server, specifying main as the module and app as the FastAPI instance. The --reload flag enables automatic reloading, which means the server will automatically restart whenever you make changes to your code. This is incredibly useful during development as it allows you to see your changes in real-time without manually restarting the server.
Accessing Your API
Once the server is running, you can access your API by opening your web browser and navigating to http://127.0.0.1:8000. You should see the following JSON response:
{"message": "Hello World"}
Congratulations! You've successfully created and run your first FastAPI application.
Adding More Endpoints
Now that you have a basic API running, let's add more endpoints to make it more interesting. We'll add an endpoint that takes a name as a parameter and returns a personalized greeting.
Creating a Parameterized Endpoint
Add the following code to your main.py file:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello World"}
@app.get("/hello/{name}")
async def read_item(name: str):
return {"message": f"Hello {name}"}
This code defines a new GET endpoint at the path /hello/{name}. The {name} part of the path is a path parameter, which means it can be any value. The read_item function takes the name parameter as input and returns a JSON response with a personalized greeting. The type annotation name: str tells FastAPI that the name parameter should be a string. FastAPI uses this information to automatically validate the input and return an error if it's not a string. This is a powerful feature of FastAPI that helps prevent errors and ensures that your API receives the correct data.
Accessing the Parameterized Endpoint
Make sure your Uvicorn server is running (if it's not, run the uvicorn main:app --reload command). Open your web browser and navigate to http://127.0.0.1:8000/hello/John. You should see the following JSON response:
{"message": "Hello John"}
You can replace "John" with any name you like, and the API will return a personalized greeting.
Using Query Parameters
In addition to path parameters, FastAPI also supports query parameters. Query parameters are key-value pairs that are appended to the URL after a question mark (?). Let's add an endpoint that uses a query parameter to filter items.
Creating an Endpoint with Query Parameters
Add the following code to your main.py file:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello World"}
@app.get("/hello/{name}")
async def read_item(name: str):
return {"message": f"Hello {name}"}
@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
This code defines a new GET endpoint at the path /items/. The read_items function takes two query parameters: skip and limit. The skip parameter specifies the number of items to skip, and the limit parameter specifies the maximum number of items to return. The default values for skip and limit are 0 and 10, respectively. The skip: int = 0 and limit: int = 10 syntax defines the query parameters and their default values. If the user doesn't provide these parameters in the URL, FastAPI will use the default values. This makes your API more flexible and user-friendly.
Accessing the Endpoint with Query Parameters
Make sure your Uvicorn server is running. Open your web browser and navigate to http://127.0.0.1:8000/items/?skip=20&limit=50. You should see the following JSON response:
{"skip": 20, "limit": 50}
You can change the values of skip and limit to see how the API responds.
Data Validation with Pydantic
FastAPI integrates seamlessly with Pydantic, a data validation library. Pydantic allows you to define data models with type annotations, and FastAPI automatically validates the input data against these models.
Creating a Pydantic Model
Let's create a Pydantic model for an item. Add the following code to your main.py file:
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return item
This code defines a Pydantic model named Item with four fields: name, description, price, and tax. The name and price fields are required, while the description and tax fields are optional (indicated by | None = None). The app.post decorator specifies that we are creating a POST endpoint to create new items. When a request is sent to /items/ FastAPI automatically validates the request body against the Item model. This automatic validation can save significant development time. If the incoming data doesn't conform to the defined model (e.g., the price is not a float), FastAPI will automatically return an error response, preventing invalid data from entering your application.
Sending Data to the Endpoint
To send data to the /items/ endpoint, you can use a tool like curl or Postman. Here's an example of how to send data using curl:
curl -X POST -H "Content-Type: application/json" -d '{"name": "Foo", "description": "A very nice Item", "price": 50.2, "tax": 3.2}' http://127.0.0.1:8000/items/
This command sends a POST request to the /items/ endpoint with a JSON payload containing the item data. The API will return the same data as a response.
Conclusion
This guide has provided a basic introduction to building APIs with FastAPI. You've learned how to set up your environment, create endpoints, use path and query parameters, and validate data with Pydantic. FastAPI offers many more features, such as authentication, middleware, and dependency injection. With its ease of use and high performance, FastAPI is an excellent choice for building modern APIs with Python. Remember to explore the official FastAPI documentation to discover more advanced features and techniques. Happy coding, guys! You're well on your way to becoming a FastAPI master! And don't forget to keep practicing and experimenting with different features to solidify your understanding. The more you build, the more comfortable you'll become with this powerful framework.