Creating Your First FastAPI Endpoint with Pydantic
In the last lesson, we set up FastAPI for data science projects. We installed FastAPI, configured the environment, and created a basic app structure. Now, it's time to dive deeper and create our first FastAPI endpoint. This lesson will teach you how to handle requests and responses using Pydantic, which is a powerful tool for data validation. By the end, you'll know how to build a simple REST API with GET and POST endpoints.
Why FastAPI and Pydantic?
I recently worked on a project where I needed to build a REST API for a data science app. The goal was to let users upload data and get predictions from a machine learning model. FastAPI made it easy to handle requests, but I faced a challenge: ensuring the data sent by users was valid. That’s where Pydantic came in. It helped me validate input data and send structured responses. For example, if a user sent a string instead of a number, Pydantic would catch the error and return a clear message. This saved me hours of debugging and made the app more reliable.
Setting Up a Basic FastAPI App
To create your first FastAPI endpoint, start by setting up a basic app. If you haven’t installed FastAPI yet, run pip install fastapi and pip install uvicorn. Then, create a file named main.py and add the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Welcome to FastAPI!"}
This code creates a simple GET endpoint at the root URL (/). When you visit this URL, it returns a JSON response with a welcome message. To run the app, use the command uvicorn main:app —reload. Open your browser and go to http://127.0.0.1:8000/ to see the message.
Adding a GET Endpoint
Now, let’s create a GET endpoint that returns data. Suppose you want to build an API that provides information about books. Here’s how you can do it:
from fastapi import FastAPI
app = FastAPI()
books = [
{"id": 1, "title": "Python for Data Science", "author": "John Doe"},
{"id": 2, "title": "FastAPI Essentials", "author": "Jane Smith"},
]
@app.get("/books")
def get_books():
return books
In this example, the /books endpoint returns a list of books. Each book is a dictionary with an ID, title, and author. This is a simple way to share data through your API.
Using Pydantic for Data Validation
Pydantic helps you validate data and define request and response models. Let’s say you want to add a POST endpoint to add new books. First, install Pydantic with pip install pydantic. Then, define a Pydantic model for the book data:
from pydantic import BaseModel
class Book(BaseModel):
id: int
title: str
author: str
Next, update your FastAPI app to use this model:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Book(BaseModel):
id: int
title: str
author: str
books = []
@app.post("/books")
def add_book(book: Book):
books.append(book)
return {"message": "Book added successfully!"}
Now, when you send a POST request to /books with a JSON body like {“id”: 3, “title”: “Data Science with FastAPI”, “author”: “Alice Brown”}, the data will be validated automatically. If the data is invalid, FastAPI will return an error.
Testing Your API
To test your API, you can use tools like Postman or FastAPI’s built-in Swagger UI. Go to http://127.0.0.1:8000/docs to see the interactive docs. Here, you can test both the GET and POST endpoints. For example, try adding a new book using the POST endpoint and then retrieve the list of books using the GET endpoint.
Conclusion: What’s Next?
In this lesson, you learned how to create your first FastAPI endpoint. We covered setting up a basic app, adding GET and POST endpoints, and using Pydantic for data validation. These skills are essential for building REST APIs for data science apps. In the next lesson, we’ll explore how to handle data with FastAPI and Pandas. You’ll learn how to process and analyze data directly within your API.
Comments
There are no comments yet.