Build A REST API With FastAPI & OpenRouter
Hey everyone! π Let's dive into creating a robust REST API using FastAPI and integrating it with OpenRouter. This guide will walk you through the entire process, from setting up the architecture to deploying your API with Docker. Whether you're a seasoned developer or just starting, this will help you get your project up and running smoothly. Let's get started!
Setting the Stage: Project Architecture and Key Components
First, let's understand the core components and how they fit together. We're going to build a system where a client interacts with our FastAPI API, which then communicates with OpenRouter to handle the heavy lifting. This design keeps things organized and scalable. π
Separated Classes: The Building Blocks
We'll have two main classes to manage different aspects of our application:
- OpenRouter Class (Existing): Located in 
app/services/openrouter.py. This class will contain the business logic and handle all the interactions with OpenRouter. Think of it as the brains of our operation, specifically focused on communicating with the OpenRouter service. - FastAPI API Class (New): Located in 
app/api/llm_api.py. This class is our HTTP communication layer, exposing REST endpoints. It will call methods from theOpenRouterclass and provide a way for clients to interact with the service through API calls. It's the face of our API. 
The Flow: How It All Works
Here's how the magic happens:
- A HTTP Client sends a request.
 - The request hits the FastAPI API.
 - The API then communicates with OpenRouter, which processes the request.
 - Optionally, the API can also communicate with other services like Ollama.
 - Swagger UI provides documentation and allows you to test your endpoints.
 
This architecture is designed to be clean, maintainable, and easy to extend. It ensures that your API remains flexible as your project grows. By separating concerns, you can make changes to one part of the system without affecting others.
Technical Deep Dive: API FastAPI Class and Endpoint Mapping
Now, let's get into the nitty-gritty of building the FastAPI API class. This class is crucial for handling HTTP requests and responses. π€
Responsibilities of the API Class
The FastAPI API class needs to handle a few key responsibilities:
- Exposing HTTP Endpoints: It's the gateway for clients, providing endpoints that clients can call to access the functionality.
 - Calling OpenRouter Methods: It will call the methods from our 
OpenRouterclass to perform the actual work. Think of it as a messenger that tellsOpenRouterwhat to do. - Swagger Documentation: We'll leverage Swagger to automatically generate API documentation, making it easy for developers to understand and use our API.
 
Endpoint Mapping: Direct Communication
We'll create a one-to-one mapping between the methods in the OpenRouter class and the endpoints in our FastAPI API. This makes the API intuitive and easy to use. For every method in OpenRouter, there will be a corresponding endpoint in our API.
No Pydantic for this Project
For this project, we'll avoid using Pydantic for data validation. This simplifies the initial setup and keeps the focus on integrating the API and OpenRouter. However, in a real-world scenario, you might want to use Pydantic to ensure data integrity.
By following these guidelines, you'll be able to create a FastAPI API that's both powerful and easy to maintain. This approach keeps your code clean and makes it easier to add new features.
Project Structure and Integration with main.py
Let's get organized and look at the project structure, and how everything comes together.
Project Directory Structure: Keeping It Clean
Here's a breakdown of the project directory structure:
carpeta-grupo/
βββ app/
β   βββ __init__.py
β   βββ main.py
β   βββ api/
β   β   βββ __init__.py
β   β   βββ llm_api.py          # FastAPI API Class
β   βββ services/
β       βββ __init__.py
β       βββ openrouter.py       # OpenRouter Class
β
βββ Dockerfile
βββ docker-compose.yml
βββ requirements.txt
βββ README.md
The app/ directory contains all of our application code. Inside, the api/ directory will hold the llm_api.py file, which contains our FastAPI API class. The services/ directory will have the openrouter.py file, containing the OpenRouter class. The other files are for Docker, and project documentation.
Registering Routes in main.py: Connecting the Dots
In the main.py file, we'll import our API class and register its routes with the FastAPI application. This step is essential for making our API accessible. Here's how you'll do it:
- Import the API class from the 
apimodule. - Create an instance of the API class.
 - Register the router in the FastAPI application.
 
This simple setup makes sure that your API is ready to serve requests. This is what you would do in your main.py file to set it up. It acts as the entry point of your application.
By ensuring that you have this directory structure and properly register your API routes in main.py, you'll have a fully functional API ready to interact with OpenRouter.
Swagger UI: Automatic Documentation and Testing
Swagger UI is a fantastic tool that automatically generates interactive API documentation. It lets you easily see what endpoints are available, what parameters they accept, and even test them directly from your browser. π
How Swagger Works
FastAPI automatically generates Swagger documentation for your API. This documentation is based on your API's endpoints, request/response models, and other metadata. This means you don't have to manually write and maintain documentation, which can be a huge time-saver.
Accessing Swagger
Once your API is running, you can access the Swagger UI by navigating to /docs in your browser (e.g., http://localhost:8000/docs). Here, you'll see a user-friendly interface that lists all your API endpoints, allowing you to easily test them. You can click on an endpoint to see more details, such as the request parameters, response format, and any associated models.
Redoc: Another Documentation Option
FastAPI also provides another documentation tool called Redoc. You can access it by going to /redoc in your browser (e.g., http://localhost:8000/redoc). Redoc provides a different style of documentation, which is equally helpful for understanding and using your API.
Endpoint Description and Grouping
The documentation will include descriptions of each endpoint and can be organized by tags. For example, you can group endpoints under tags like