To deploy your microservice, you'll need to containerize it using Docker. Create a new file called Dockerfile and add the following code:
from fastapi import APIRouter, Depends from pydantic import BaseModel from database import engine, User as DBUser
Base.metadata.create_all(engine) This code sets up a SQLite database and defines a User model using SQLAlchemy.
class User(BaseModel): username: str email: str password: str
FROM python:3.9-slim
FROM python:3.9-slim
WORKDIR /app
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String
from fastapi import APIRouter, Depends from pydantic import BaseModel
Build your Docker image:
@router.post("/users/") def create_user(user: User): db_user = DBUser(username=user.username, email=user.email, password=user.password) # Save user to database db_session = engine.connect() db_session.execute("INSERT INTO users (username, email, password) VALUES (:username, :email, :password)", {"username": user.username, "email": user.email, "password": user.password}) db_session.close() return {"message": f"User {user.username} created successfully"} This code connects to the database and saves the user data.
Update the users.py file to use the database:
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"] This code creates a Docker image for your microservice.
Create a new directory for your project and navigate to it in your terminal or command prompt:
