{"id":403,"date":"2024-03-06T22:05:47","date_gmt":"2024-03-06T16:35:47","guid":{"rendered":"https:\/\/mrcoder701.com\/?p=403"},"modified":"2024-03-15T16:55:25","modified_gmt":"2024-03-15T11:25:25","slug":"database-integration-fastapi-guide","status":"publish","type":"post","link":"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/","title":{"rendered":"Database Integration with FastAPI"},"content":{"rendered":"

Adding a database integration to your web application is like giving it superpowers; all of a sudden, it can remember, change, and communicate with a plethora of data. FastAPI, renowned for its excellent performance and user-friendliness, further streamlines this procedure. This book will help you integrate databases with FastAPI without any problems, regardless of your level of experience. It’s perfect for beginners who want to get their hands dirty or seasoned developers who want to brush up on the latest techniques.<\/p>

This article will guide you through every step of setting up your database integration FastAPI project, including selecting the appropriate database, configuring your database models, and carrying out CRUD activities. Upon completion, you will possess a firm grasp on how to integrate your FastAPI application with a database, along with code samples that will expedite your start-up process.<\/p>

Step 1: Set Up Your FastAPI Project<\/h2>

First, make sure that Uvicorn, an ASGI server, and FastAPI are installed. If not, pip can be used to install them:<\/p>

<\/circle><\/circle><\/circle><\/g><\/svg><\/span><\/path><\/path><\/svg><\/span>
python<\/span> <\/span>-<\/span>m<\/span> <\/span>venv<\/span> <\/span>venv<\/span><\/span>\nsource<\/span> <\/span>venv<\/span>\/<\/span>bin<\/span>\/<\/span>activate<\/span> # <\/span>On<\/span> <\/span>Windows<\/span> <\/span>use<\/span> <\/span>`<\/span>venv<\/span>\\S<\/span>cripts<\/span>\\a<\/span>ctivate<\/span>`<\/span><\/span>\npip<\/span> <\/span>install<\/span> <\/span>fastapi<\/span> <\/span>uvicorn<\/span><\/span><\/code><\/pre><\/div>

We’re integrating databases with SQLAlchemy in this lesson. Install it together with the database driver for your database (asyncpg is suggested for PostgreSQL, for example):<\/p>

<\/circle><\/circle><\/circle><\/g><\/svg><\/span><\/path><\/path><\/svg><\/span>
pip<\/span> <\/span>install<\/span> <\/span>sqlalchemy<\/span> <\/span>asyncpg<\/span> <\/span>alembic<\/span><\/span><\/code><\/pre><\/div>

Enhanced Directory Structure<\/h2>

Here\u2019s a recommended structure for a FastAPI project with database integration:<\/p>

<\/circle><\/circle><\/circle><\/g><\/svg><\/span><\/path><\/path><\/svg><\/span>
fastapi_project<\/span>\/<\/span><\/span>\n\u251c\u2500\u2500 <\/span>venv<\/span>\/<\/span><\/span>\n\u2514\u2500\u2500 <\/span>app<\/span>\/<\/span><\/span>\n    \u251c\u2500\u2500 <\/span>__init__<\/span>.<\/span>py<\/span><\/span>\n    \u251c\u2500\u2500 <\/span>main<\/span>.<\/span>py<\/span><\/span>\n    \u251c\u2500\u2500 <\/span>models<\/span>.<\/span>py<\/span><\/span>\n    \u2514\u2500\u2500 <\/span>database<\/span>.<\/span>py<\/span><\/span><\/code><\/pre><\/div>

Step 2: Define Your Database Models<\/h2>

Let’s create a simple model for a User<\/code>. Define your SQLAlchemy model in a file named models.py<\/code>. Since FastAPI 0.79.0 to 0.108.0 introduced support for SQLAlchemy 2.0’s new style, we’ll use that:<\/p>

In app\/models.py<\/code>, define your SQLAlchemy models:<\/p>

<\/circle><\/circle><\/circle><\/g><\/svg><\/span><\/path><\/path><\/svg><\/span>
from<\/span> <\/span>sqlalchemy<\/span> <\/span>import<\/span> <\/span>Column<\/span>,<\/span> <\/span>Integer<\/span>,<\/span> <\/span>String<\/span><\/span>\nfrom<\/span> <\/span>sqlalchemy<\/span>.<\/span>orm<\/span> <\/span>import<\/span> <\/span>declarative_base<\/span>,<\/span> <\/span>Mapped<\/span><\/span>\n<\/span>\nBase<\/span> = <\/span>declarative_base<\/span>()<\/span><\/span>\n<\/span>\nclass<\/span> <\/span>User<\/span>(<\/span>Base<\/span>):<\/span><\/span>\n    <\/span>__tablename__<\/span> = <\/span>'<\/span>users<\/span>'<\/span><\/span>\n<\/span>\n    <\/span>id<\/span>: <\/span>Mapped<\/span>[<\/span>int<\/span>] = <\/span>Column<\/span>(<\/span>Integer<\/span>,<\/span> <\/span>primary_key<\/span>=<\/span>True<\/span>,<\/span> <\/span>index<\/span>=<\/span>True<\/span>)<\/span><\/span>\n    <\/span>name<\/span>: <\/span>Mapped<\/span>[<\/span>str<\/span>] = <\/span>Column<\/span>(<\/span>String<\/span>,<\/span> <\/span>index<\/span>=<\/span>True<\/span>)<\/span><\/span>\n    <\/span>email<\/span>: <\/span>Mapped<\/span>[<\/span>str<\/span>] = <\/span>Column<\/span>(<\/span>String<\/span>,<\/span> <\/span>unique<\/span>=<\/span>True<\/span>,<\/span> <\/span>index<\/span>=<\/span>True<\/span>)<\/span><\/span>\n<\/span><\/code><\/pre><\/div>
  • Column, Integer, String<\/code><\/strong>: These are imported from sqlalchemy<\/code>. Column<\/code> is used to define a column in a database table. Integer<\/code> and String<\/code> are types that specify what kind of data each column will store (integer numbers and strings of characters, respectively).<\/li>\n\n
  • declarative_base<\/code><\/strong>: This function returns a base class for declarative class definitions. The class we define will inherit from this base class, and SQLAlchemy will recognize it as a model that should be mapped to a database table.<\/li>\n\n
  • Mapped<\/code><\/strong>: This is a typing hint introduced in SQLAlchemy 1.4 for type checking and editor support. It informs type checkers that these attributes are SQLAlchemy column objects which are mapped to database columns.<\/li>\n\n
  • Base = declarative_base()<\/code><\/strong>: This line creates a base class for the declarative class definition. All model classes should inherit from this Base<\/code> class. It contains a MetaData object where newly defined Table objects are collected.<\/li>\n\n
  • class User(Base)<\/code><\/strong>: This defines a new class User<\/code> that inherits from Base<\/code>. This class represents a table in the database.<\/li>\n\n
  • __tablename__ = 'users'<\/code><\/strong>: This attribute is required by SQLAlchemy to know the table name in the database that this class will be mapped to.<\/li>\n\n
  • Attributes with Mapped[Type]<\/code><\/strong>: Each attribute of the class represents a column in the database table. The type of each attribute (e.g., int<\/code> for id<\/code>, str<\/code> for name<\/code> and email<\/code>) is specified using Mapped[Type]<\/code>, which also enables better type hinting and editor support.<\/li>\n\n
  • Column(...)<\/code><\/strong>: This function is used to define a column. The first argument specifies the column’s data type.<\/li>\n\n
  • primary_key=True<\/code><\/strong>: This indicates that id<\/code> is the primary key of the table.<\/li>\n\n
  • index=True<\/code><\/strong>: This means an index will be created for this column, improving query performance on this column.<\/li>\n\n
  • unique=True<\/code><\/strong>: For the email<\/code> column, this ensures that all values in this column are unique across the table.<\/li><\/ul>

    Step 3: Establish Database Connection<\/h3>

    In a new file, database.py<\/code>, set up your database connection using SQLAlchemy’s create_async_engine<\/code> and sessionmaker<\/code> for asynchronous communication <\/p>

    Create app\/database.py<\/code> to set up database connectivity:<\/p>

    <\/circle><\/circle><\/circle><\/g><\/svg><\/span><\/path><\/path><\/svg><\/span>
    # <\/span>database<\/span>.<\/span>py<\/span><\/span>\n<\/span>\nfrom<\/span> <\/span>sqlalchemy<\/span> <\/span>import<\/span> <\/span>create_engine<\/span><\/span>\nfrom<\/span> <\/span>sqlalchemy<\/span>.<\/span>ext<\/span>.<\/span>declarative<\/span> <\/span>import<\/span> <\/span>declarative_base<\/span><\/span>\nfrom<\/span> <\/span>sqlalchemy<\/span>.<\/span>orm<\/span> <\/span>import<\/span> <\/span>sessionmaker<\/span><\/span>\n<\/span>\nSQLALCHEMY_DATABASE_URL<\/span> = <\/span>"<\/span>sqlite:\/\/\/.\/test.db<\/span>"<\/span><\/span>\n# <\/span>For<\/span> <\/span>other<\/span> <\/span>databases<\/span> <\/span>like<\/span> <\/span>PostgreSQL<\/span>,<\/span> <\/span>use<\/span> <\/span>the<\/span> <\/span>appropriate<\/span> <\/span>URL<\/span><\/span>\n<\/span>\nengine<\/span> = <\/span>create_engine<\/span>(<\/span><\/span>\n    <\/span>SQLALCHEMY_DATABASE_URL<\/span>,<\/span> <\/span>connect_args<\/span>=<\/span>{<\/span>"<\/span>check_same_thread<\/span>": <\/span>False<\/span>}<\/span><\/span>\n)<\/span><\/span>\nSessionLocal<\/span> = <\/span>sessionmaker<\/span>(<\/span>autocommit<\/span>=<\/span>False<\/span>,<\/span> <\/span>autoflush<\/span>=<\/span>False<\/span>,<\/span> <\/span>bind<\/span>=<\/span>engine<\/span>)<\/span><\/span>\n<\/span>\nBase<\/span> = <\/span>declarative_base<\/span>()<\/span><\/span>\n<\/span>\n<\/span><\/code><\/pre><\/div>
    • create_engine<\/code><\/strong>: This function from SQLAlchemy is used to create an engine that manages connections to the database. The engine is the starting point for any SQLAlchemy application.<\/li>\n\n
    • declarative_base<\/code><\/strong>: This function returns a base class for class-based model definitions. Each model you create will inherit from this base class.<\/li>\n\n
    • sessionmaker<\/code><\/strong>: This is a factory for session objects. A session in SQLAlchemy represents a \u201cwork area\u201d for your objects, where you can query and manipulate data before committing those changes to the database<\/li>\n\n
    • SQLALCHEMY_DATABASE_URL<\/code><\/strong>: This string represents the connection URL to your database. In this example, it’s configured to connect to a SQLite database named test.db<\/code> located in the same directory as your project. For other databases like PostgreSQL, you would change this URL accordingly.<\/li>\n\n
    • create_engine(...)<\/code><\/strong>: This line creates an engine instance that knows how to connect to your database using the URL provided. The connect_args<\/code> parameter is specific to SQLite and is used to allow the same thread to be used by multiple requests in development. For other databases, this parameter might not be needed or different parameters may be required.<\/li>\n\n
    • sessionmaker(...)<\/code><\/strong>: This creates a factory (named SessionLocal<\/code> here) that will generate new Session<\/code> objects when called, bound to the engine<\/code> we previously created. autocommit=False<\/code> means that changes made through the session won’t be committed automatically, giving you control over when to commit transactions. autoflush=False<\/code> means SQLAlchemy won’t automatically flush database changes (sending pending changes to the database) before each query.<\/li>\n\n
    • declarative_base()<\/code><\/strong>: This creates a base class for your declarative class definitions. Every model you create will inherit from this Base<\/code> class, which associates it with the engine, allowing SQLAlchemy to discover and map the database schema.<\/li><\/ul>

      Creating Database Tables<\/h3>

      Before running the app, ensure the database tables are created. You can use main.py<\/code> to create tables based on your models.<\/p>

      <\/circle><\/circle><\/circle><\/g><\/svg><\/span><\/path><\/path><\/svg><\/span>
      # <\/span>main<\/span>.<\/span>py<\/span><\/span>\n<\/span>\nfrom<\/span> <\/span>fastapi<\/span> <\/span>import<\/span> <\/span>FastAPI<\/span><\/span>\nfrom<\/span> <\/span>sqlalchemy<\/span>.<\/span>orm<\/span> <\/span>import<\/span> <\/span>Session<\/span><\/span>\nfrom<\/span> <\/span>database<\/span> <\/span>import<\/span> <\/span>SessionLocal<\/span>,<\/span> <\/span>engine<\/span><\/span>\nimport<\/span> <\/span>models<\/span><\/span>\n<\/span>\nmodels<\/span>.<\/span>Base<\/span>.<\/span>metadata<\/span>.<\/span>create_all<\/span>(<\/span>bind<\/span>=<\/span>engine<\/span>)<\/span><\/span>\n<\/span>\napp<\/span> = <\/span>FastAPI<\/span>()<\/span><\/span><\/code><\/pre><\/div>

      The main.py<\/code> script in your FastAPI application is where the web application instance is created and configured. It also plays a critical role in initializing your database models and setting up the application’s endpoints. Here’s a breakdown of the code snippet provided:<\/p>

      • from fastapi import FastAPI<\/code><\/strong>: Imports the FastAPI class, which is used to create your web application instance.<\/li>\n\n
      • from sqlalchemy.orm import Session<\/code><\/strong>: Imports the Session class from SQLAlchemy, which will be used for database sessions to execute queries.<\/li>\n\n
      • from database import SessionLocal, engine<\/code><\/strong>: Imports the SessionLocal<\/code> (a factory for creating new session objects) and engine<\/code> (your database engine) from your database.py<\/code> file.<\/li>\n\n
      • import models<\/code><\/strong>: Imports the models<\/code> module, which contains your SQLAlchemy models (tables).<\/li>\n\n
      • models.Base.metadata.create_all(bind=engine)<\/code><\/strong>: This line is crucial. It tells SQLAlchemy to create all tables defined in your models (inherited from Base<\/code>) that do not already exist in the database. The bind=engine<\/code> argument specifies which engine (database connection) to use for creating the tables. This is how your database schema is applied to the actual database, allowing you to work with the defined tables in your application.<\/li>\n\n
      • app = FastAPI()<\/code><\/strong>: Creates an instance of the FastAPI application. This app<\/code> object is used to create routes and handle requests. After defining app<\/code>, you would typically go on to define various endpoints (API routes) that allow clients to interact with your application by performing actions like reading from or writing to your database.<\/li><\/ul>

        CRUD Examples<\/h3>

        Create a New User<\/h4>

        To create a new user, we’ll use a POST request.<\/p>

        <\/circle><\/circle><\/circle><\/g><\/svg><\/span><\/path><\/path><\/svg><\/span>
        from<\/span> <\/span>fastapi<\/span> <\/span>import<\/span> <\/span>FastAPI<\/span>,<\/span> <\/span>Depends<\/span>,<\/span> <\/span>HTTPException<\/span><\/span>\nfrom<\/span> <\/span>sqlalchemy<\/span>.<\/span>orm<\/span> <\/span>import<\/span> <\/span>Session<\/span><\/span>\nfrom<\/span> .<\/span>models<\/span> <\/span>import<\/span> <\/span>User<\/span><\/span>\nfrom<\/span> .<\/span>database<\/span> <\/span>import<\/span> <\/span>SessionLocal<\/span><\/span>\nfrom<\/span> <\/span>pydantic<\/span> <\/span>import<\/span> <\/span>BaseModel<\/span><\/span>\n<\/span>\ndef<\/span> <\/span>get_db<\/span>():<\/span><\/span>\n    <\/span>db<\/span> = <\/span>SessionLocal<\/span>()<\/span><\/span>\n    <\/span>try<\/span>:<\/span><\/span>\n        <\/span>yield<\/span> <\/span>db<\/span><\/span>\n    <\/span>finally<\/span>:<\/span><\/span>\n        <\/span>db<\/span>.<\/span>close<\/span>()<\/span><\/span>\n<\/span>\nclass<\/span> <\/span>UserCreate<\/span>(<\/span>BaseModel<\/span>):<\/span><\/span>\n    <\/span>"""<\/span><\/span>\n      UserCreate defines the expected request body for creating a new user<\/span>.<\/span><\/span>\n      <\/span>It<\/span> <\/span>uses<\/span> <\/span>Pydantic<\/span> <\/span>models<\/span> <\/span>for<\/span> <\/span>data<\/span> <\/span>validation<\/span>.<\/span><\/span>\n      <\/span><\/span>\n      <\/span>Attributes<\/span>:<\/span><\/span>\n          <\/span>name<\/span> (<\/span>str<\/span>): <\/span>The<\/span> <\/span>name<\/span> <\/span>of<\/span> <\/span>the<\/span> <\/span>user<\/span>.<\/span><\/span>\n          <\/span>email<\/span> (<\/span>str<\/span>): <\/span>The<\/span> <\/span>email<\/span> <\/span>address<\/span> <\/span>of<\/span> <\/span>the<\/span> <\/span>user<\/span>. <\/span>It<\/span> <\/span>must<\/span> <\/span>be<\/span> <\/span>unique<\/span>.<\/span><\/span>\n    <\/span>"""<\/span><\/span>\n   <\/span> <\/span><\/span>\n    <\/span>name<\/span>: <\/span>str<\/span><\/span>\n    <\/span>email<\/span>: <\/span>str<\/span><\/span>\n<\/span>\n@<\/span>app<\/span>.<\/span>post<\/span>(<\/span>"<\/span>\/users\/<\/span>"<\/span>,<\/span> <\/span>response_model<\/span>=<\/span>UserCreate<\/span>)<\/span><\/span>\ndef<\/span> <\/span>create_user<\/span>(<\/span>user<\/span>: <\/span>UserCreate<\/span>,<\/span> <\/span>db<\/span>: <\/span>Session<\/span> = <\/span>Depends<\/span>(<\/span>get_db<\/span>)):<\/span><\/span>\n    <\/span>"""<\/span><\/span>\n    Creates a new user in the database<\/span>.<\/span><\/span>\n<\/span>\n    <\/span>Parameters<\/span>:<\/span><\/span>\n        <\/span>user<\/span> (<\/span>UserCreate<\/span>): <\/span>The<\/span> <\/span>user<\/span> <\/span>data<\/span> <\/span>sent<\/span> <\/span>by<\/span> <\/span>the<\/span> <\/span>client<\/span>.<\/span><\/span>\n        <\/span>db<\/span> (<\/span>Session<\/span>,<\/span> <\/span>optional<\/span>): <\/span>The<\/span> <\/span>database<\/span> <\/span>session<\/span> <\/span>used<\/span> <\/span>to<\/span> <\/span>execute<\/span> <\/span>database<\/span> <\/span>operations<\/span>. <\/span><\/span>\n                                <\/span>It<\/span>'<\/span>s injected by FastAPI<\/span>'<\/span>s<\/span> <\/span>Depends<\/span> <\/span>mechanism<\/span>.<\/span><\/span>\n<\/span>\n    <\/span>Returns<\/span>:<\/span><\/span>\n        <\/span>User<\/span> <\/span>instance<\/span> <\/span>that<\/span> <\/span>was<\/span> <\/span>added<\/span> <\/span>to<\/span> <\/span>the<\/span> <\/span>database<\/span>.<\/span><\/span>\n    <\/span>"""<\/span><\/span>\n   <\/span> <\/span><\/span>\n    <\/span>db_user<\/span> = <\/span>db<\/span>.<\/span>query<\/span>(<\/span>User<\/span>).<\/span>filter<\/span>(<\/span>User<\/span>.<\/span>email<\/span> == <\/span>user<\/span>.<\/span>email<\/span>).<\/span>first<\/span>()<\/span><\/span>\n    <\/span>if<\/span> <\/span>db_user<\/span>:<\/span><\/span>\n        <\/span>raise<\/span> <\/span>HTTPException<\/span>(<\/span>status_code<\/span>=400<\/span>,<\/span> <\/span>detail<\/span>=<\/span>"<\/span>Email already registered<\/span>"<\/span>)<\/span><\/span>\n    <\/span>db_user<\/span> = <\/span>User<\/span>(<\/span>name<\/span>=<\/span>user<\/span>.<\/span>name<\/span>,<\/span> <\/span>email<\/span>=<\/span>user<\/span>.<\/span>email<\/span>)<\/span><\/span>\n    <\/span>db<\/span>.<\/span>add<\/span>(<\/span>db_user<\/span>)<\/span><\/span>\n    <\/span>db<\/span>.<\/span>commit<\/span>()<\/span><\/span>\n    <\/span>db<\/span>.<\/span>refresh<\/span>(<\/span>db_user<\/span>)<\/span><\/span>\n    <\/span>return<\/span> <\/span>db_user<\/span><\/span>\n<\/span><\/code><\/pre><\/div>

        Read Operations<\/h4>
        • Get a Single User by ID<\/strong><\/li><\/ul>
          <\/circle><\/circle><\/circle><\/g><\/svg><\/span><\/path><\/path><\/svg><\/span>
          @<\/span>app<\/span>.<\/span>get<\/span>(<\/span>"<\/span>\/users\/{user_id}<\/span>"<\/span>)<\/span><\/span>\ndef<\/span> <\/span>read_user<\/span>(<\/span>user_id<\/span>: <\/span>int<\/span>,<\/span> <\/span>db<\/span>: <\/span>Session<\/span> <\/span>=<\/span> <\/span>Depends<\/span>(<\/span>get_db<\/span>)):<\/span><\/span>\n    <\/span>"""<\/span><\/span>\n      Retrieves a user by their user_id from the database<\/span>.<\/span><\/span>\n      <\/span><\/span>\n      Parameters<\/span>:<\/span><\/span>\n          <\/span>user_id<\/span> (<\/span>int<\/span>): <\/span>The<\/span> <\/span>unique<\/span> <\/span>identifier<\/span> <\/span>of<\/span> <\/span>the<\/span> <\/span>user<\/span> <\/span>to<\/span> <\/span>retrieve<\/span>.<\/span><\/span>\n          <\/span>db<\/span> (<\/span>Session<\/span>): <\/span>The<\/span> <\/span>database<\/span> <\/span>session<\/span> <\/span>used<\/span> <\/span>to<\/span> <\/span>execute<\/span> <\/span>database<\/span> <\/span>operations<\/span>.<\/span> <\/span><\/span>\n                        <\/span>This<\/span> <\/span>session<\/span> <\/span>is<\/span> <\/span>automatically<\/span> <\/span>provided<\/span> <\/span>by<\/span> <\/span>FastAPI<\/span>'<\/span>s dependency injection<\/span>.<\/span><\/span>\n      <\/span><\/span>\n      Returns<\/span>:<\/span><\/span>\n          <\/span>The<\/span> <\/span>user<\/span> <\/span>instance<\/span> <\/span>identified<\/span> <\/span>by<\/span> <\/span>user_id<\/span>.<\/span> <\/span>If<\/span> <\/span>no<\/span> <\/span>user<\/span> <\/span>is<\/span> <\/span>found<\/span> <\/span>with<\/span> <\/span>the<\/span> <\/span>provided<\/span> <\/span>ID<\/span>,<\/span><\/span>\n          <\/span>a<\/span> <\/span>404<\/span> <\/span>error<\/span> <\/span>is<\/span> <\/span>raised<\/span> <\/span>indicating<\/span> <\/span>that<\/span> <\/span>the<\/span> <\/span>user<\/span> <\/span>is<\/span> <\/span>not<\/span> <\/span>found<\/span>.<\/span><\/span>\n      <\/span><\/span>\n      Raises<\/span>:<\/span><\/span>\n          HTTPException<\/span>:<\/span> <\/span>A<\/span> <\/span>404<\/span> <\/span>status<\/span> <\/span>code<\/span> <\/span>is<\/span> <\/span>raised<\/span> <\/span>if<\/span> <\/span>no<\/span> <\/span>user<\/span> <\/span>with<\/span> <\/span>the<\/span> <\/span>given<\/span> <\/span>user_id<\/span> <\/span>exists<\/span> <\/span>in<\/span> <\/span>the<\/span> <\/span>database<\/span>.<\/span><\/span>\n    <\/span>"""<\/span><\/span>\n   <\/span> <\/span><\/span>\n    <\/span>db_user<\/span> <\/span>=<\/span> <\/span>db<\/span>.<\/span>query<\/span>(<\/span>User<\/span>)<\/span>.<\/span>filter<\/span>(<\/span>User<\/span>.<\/span>id<\/span> <\/span>==<\/span> <\/span>user_id<\/span>)<\/span>.<\/span>first<\/span>()<\/span><\/span>\n    <\/span>if<\/span> <\/span>db_user<\/span> <\/span>is<\/span> None<\/span>:<\/span><\/span>\n        <\/span>raise<\/span> <\/span>HTTPException<\/span>(<\/span>status_code<\/span>=<\/span>404<\/span>,<\/span> <\/span>detail<\/span>=<\/span>"<\/span>User not found<\/span>"<\/span>)<\/span><\/span>\n    <\/span>return<\/span> <\/span>db_user<\/span><\/span><\/code><\/pre><\/div>

          Get All Users<\/strong><\/p>

          <\/circle><\/circle><\/circle><\/g><\/svg><\/span><\/path><\/path><\/svg><\/span>
          @<\/span>app<\/span>.<\/span>get<\/span>(<\/span>"<\/span>\/users\/<\/span>"<\/span>)<\/span><\/span>\ndef<\/span> <\/span>read_users<\/span>(<\/span>skip<\/span>: <\/span>int<\/span> <\/span>=<\/span> <\/span>0<\/span>,<\/span> <\/span>limit<\/span>: <\/span>int<\/span> <\/span>=<\/span> <\/span>10<\/span>,<\/span> <\/span>db<\/span>: <\/span>Session<\/span> <\/span>=<\/span> <\/span>Depends<\/span>(<\/span>get_db<\/span>)):<\/span><\/span>\n    <\/span>"""<\/span><\/span>\n    Retrieves a list of users from the database, with pagination support<\/span>.<\/span><\/span>\n    <\/span><\/span>\n    <\/span>This<\/span> <\/span>endpoint<\/span> <\/span>supports<\/span> <\/span>pagination<\/span> <\/span>through<\/span> <\/span>`<\/span>skip<\/span>`<\/span> <\/span>and<\/span> <\/span>`<\/span>limit<\/span>`<\/span> <\/span>parameters<\/span>,<\/span><\/span>\n    <\/span>allowing<\/span> <\/span>for<\/span> <\/span>a<\/span> <\/span>scalable<\/span> <\/span>way<\/span> <\/span>to<\/span> <\/span>fetch<\/span> <\/span>users<\/span>.<\/span> <\/span>By<\/span> <\/span>default<\/span>,<\/span> <\/span>it<\/span> <\/span>returns<\/span> <\/span>the<\/span> <\/span>first<\/span><\/span>\n    <\/span>10<\/span> <\/span>users<\/span>.<\/span> <\/span>Adjust<\/span> <\/span>`<\/span>skip<\/span>`<\/span> <\/span>and<\/span> <\/span>`<\/span>limit<\/span>`<\/span> <\/span>to<\/span> <\/span>retrieve<\/span> <\/span>other<\/span> <\/span>users<\/span> <\/span>or<\/span> <\/span>to<\/span> <\/span>change<\/span> <\/span>the<\/span><\/span>\n    <\/span>number<\/span> <\/span>of<\/span> <\/span>users<\/span> <\/span>returned<\/span> <\/span>in<\/span> <\/span>a<\/span> <\/span>single<\/span> <\/span>request<\/span>.<\/span><\/span>\n    <\/span><\/span>\n    Parameters<\/span>:<\/span><\/span>\n        <\/span>skip<\/span> (<\/span>int<\/span>): <\/span>The<\/span> <\/span>number<\/span> <\/span>of<\/span> <\/span>records<\/span> <\/span>to<\/span> <\/span>skip<\/span> <\/span>before<\/span> <\/span>starting<\/span> <\/span>to<\/span> <\/span>collect<\/span> <\/span>the<\/span><\/span>\n                    <\/span>result<\/span> <\/span>set<\/span>.<\/span> <\/span>Defaults<\/span> <\/span>to<\/span> <\/span>0.<\/span><\/span>\n        <\/span>limit<\/span> (<\/span>int<\/span>): <\/span>The<\/span> <\/span>maximum<\/span> <\/span>number<\/span> <\/span>of<\/span> <\/span>users<\/span> <\/span>to<\/span> <\/span>return<\/span>.<\/span> <\/span>Defaults<\/span> <\/span>to<\/span> <\/span>10.<\/span><\/span>\n        <\/span>db<\/span> (<\/span>Session<\/span>): <\/span>The<\/span> <\/span>database<\/span> <\/span>session<\/span> <\/span>used<\/span> <\/span>to<\/span> <\/span>execute<\/span> <\/span>database<\/span> <\/span>operations<\/span>.<\/span><\/span>\n                      <\/span>Provided<\/span> <\/span>by<\/span> <\/span>FastAPI<\/span>'<\/span>s dependency injection system<\/span>.<\/span><\/span>\n    <\/span><\/span>\n    Returns<\/span>:<\/span><\/span>\n        <\/span>A<\/span> <\/span>list<\/span> <\/span>of<\/span> <\/span>user<\/span> <\/span>instances<\/span> <\/span>up<\/span> <\/span>to<\/span> <\/span>the<\/span> <\/span>specified<\/span> <\/span>`<\/span>limit<\/span>`<\/span>,<\/span> <\/span>starting<\/span> <\/span>after<\/span><\/span>\n        <\/span>`<\/span>skip<\/span>`<\/span> <\/span>number<\/span> <\/span>of<\/span> <\/span>users<\/span>.<\/span> <\/span>If<\/span> <\/span>no<\/span> <\/span>users<\/span> <\/span>are<\/span> <\/span>found<\/span>,<\/span> <\/span>returns<\/span> <\/span>an<\/span> <\/span>empty<\/span> <\/span>list<\/span>.<\/span><\/span>\n    <\/span>"""<\/span><\/span>\n    users = db.query(User).offset(skip).limit(limit).all(<\/span>)<\/span><\/span>\n    <\/span>return<\/span> <\/span>users<\/span><\/span><\/code><\/pre><\/div>

          Update a User<\/h4>

          To update a user, we use a PUT request. We’ll update the user’s name and email for simplicity.<\/p>

          <\/circle><\/circle><\/circle><\/g><\/svg><\/span><\/path><\/path><\/svg><\/span>
          class<\/span> <\/span>UserUpdate<\/span>(<\/span>BaseModel<\/span>):<\/span><\/span>\n    """<\/span><\/span>\n    <\/span>UserUpdate<\/span> <\/span>is<\/span> <\/span>used<\/span> <\/span>for<\/span> <\/span>updating<\/span> <\/span>existing<\/span> <\/span>users<\/span> <\/span>in<\/span> <\/span>the<\/span> <\/span>database<\/span>.<\/span><\/span>\n    <\/span>It<\/span> <\/span>defines<\/span> <\/span>the<\/span> <\/span>structure<\/span> <\/span>of<\/span> <\/span>the<\/span> <\/span>request<\/span> <\/span>body<\/span> <\/span>with<\/span> <\/span>fields<\/span> <\/span>that<\/span> <\/span>can<\/span> <\/span>be<\/span> <\/span>updated<\/span>.<\/span><\/span>\n    <\/span><\/span>\n    <\/span>Attributes<\/span>:<\/span><\/span>\n        <\/span>name<\/span> (<\/span>str<\/span>): <\/span>The<\/span> <\/span>new<\/span> <\/span>name<\/span> <\/span>of<\/span> <\/span>the<\/span> <\/span>user<\/span>.<\/span><\/span>\n        <\/span>email<\/span> (<\/span>str<\/span>): <\/span>The<\/span> <\/span>new<\/span> <\/span>email<\/span> <\/span>address<\/span> <\/span>of<\/span> <\/span>the<\/span> <\/span>user<\/span>. <\/span>It<\/span> <\/span>must<\/span> <\/span>remain<\/span> <\/span>unique<\/span>.<\/span><\/span>\n    """<\/span><\/span>\n    <\/span><\/span>\n    <\/span>name<\/span>: <\/span>str<\/span><\/span>\n    <\/span>email<\/span>: <\/span>str<\/span><\/span>\n<\/span>\n<\/span>\n@<\/span>app<\/span>.<\/span>put<\/span>("\/<\/span>users<\/span>\/<\/span>{<\/span>user_id<\/span>}<\/span>"<\/span>)<\/span><\/span>\ndef<\/span> <\/span>update_user<\/span>(<\/span>user_id<\/span>: <\/span>int<\/span>,<\/span> <\/span>user<\/span>: <\/span>UserUpdate<\/span>,<\/span> <\/span>db<\/span>: <\/span>Session<\/span> <\/span>=<\/span> <\/span>Depends<\/span>(<\/span>get_db<\/span>)):<\/span><\/span>\n    <\/span>"""<\/span><\/span>\n    Updates an existing user's information in the database<\/span>.<\/span><\/span>\n    <\/span><\/span>\n    Parameters<\/span>:<\/span><\/span>\n        <\/span>user_id<\/span> (<\/span>int<\/span>): <\/span>The<\/span> <\/span>unique<\/span> <\/span>identifier<\/span> <\/span>of<\/span> <\/span>the<\/span> <\/span>user<\/span> <\/span>to<\/span> <\/span>update<\/span>.<\/span><\/span>\n        <\/span>user<\/span> (<\/span>UserUpdate<\/span>): <\/span>An<\/span> <\/span>object<\/span> <\/span>containing<\/span> <\/span>the<\/span> <\/span>updated<\/span> <\/span>user<\/span> <\/span>data<\/span>.<\/span><\/span>\n        <\/span>db<\/span> (<\/span>Session<\/span>): <\/span>The<\/span> <\/span>database<\/span> <\/span>session<\/span> <\/span>used<\/span> <\/span>to<\/span> <\/span>execute<\/span> <\/span>database<\/span> <\/span>operations<\/span>.<\/span> <\/span><\/span>\n                      <\/span>This<\/span> <\/span>session<\/span> <\/span>is<\/span> <\/span>automatically<\/span> <\/span>provided<\/span> <\/span>by<\/span> <\/span>FastAPI<\/span>'<\/span>s dependency injection<\/span>.<\/span><\/span>\n    <\/span><\/span>\n    Returns<\/span>:<\/span><\/span>\n        <\/span>The<\/span> <\/span>updated<\/span> <\/span>user<\/span> <\/span>instance<\/span> <\/span>if<\/span> <\/span>the<\/span> <\/span>update<\/span> <\/span>is<\/span> <\/span>successful<\/span>.<\/span><\/span>\n    <\/span><\/span>\n    Raises<\/span>:<\/span><\/span>\n        HTTPException<\/span>:<\/span> <\/span>A<\/span> <\/span>404<\/span> <\/span>status<\/span> <\/span>code<\/span> <\/span>is<\/span> <\/span>raised<\/span> <\/span>if<\/span> <\/span>no<\/span> <\/span>user<\/span> <\/span>with<\/span> <\/span>the<\/span> <\/span>given<\/span> <\/span>user_id<\/span> <\/span>exists<\/span>.<\/span><\/span>\n    <\/span>"""<\/span><\/span>\n   <\/span> <\/span><\/span>\n    <\/span>db_user<\/span> <\/span>=<\/span> <\/span>db<\/span>.<\/span>query<\/span>(<\/span>User<\/span>)<\/span>.<\/span>filter<\/span>(<\/span>User<\/span>.<\/span>id<\/span> <\/span>==<\/span> <\/span>user_id<\/span>)<\/span>.<\/span>first<\/span>()<\/span><\/span>\n    <\/span>if<\/span> <\/span>not<\/span> db_user<\/span>:<\/span><\/span>\n        <\/span>raise<\/span> <\/span>HTTPException<\/span>(<\/span>status_code<\/span>=<\/span>404<\/span>,<\/span> <\/span>detail<\/span>=<\/span>"<\/span>User not found<\/span>"<\/span>)<\/span><\/span>\n    <\/span>db_user<\/span>.<\/span>name<\/span> <\/span>=<\/span> <\/span>user<\/span>.<\/span>name<\/span><\/span>\n    <\/span>db_user<\/span>.<\/span>email<\/span> <\/span>=<\/span> <\/span>user<\/span>.<\/span>email<\/span><\/span>\n    <\/span>db<\/span>.<\/span>commit<\/span>()<\/span><\/span>\n    <\/span>db<\/span>.<\/span>refresh<\/span>(<\/span>db_user<\/span>)<\/span><\/span>\n    <\/span>return<\/span> <\/span>db_user<\/span><\/span>\n<\/span><\/code><\/pre><\/div>

          Delete a User<\/h4>

          To delete a user, we’ll use a DELETE request.<\/p>

          <\/circle><\/circle><\/circle><\/g><\/svg><\/span><\/path><\/path><\/svg><\/span>
          @<\/span>app<\/span>.<\/span>delete<\/span>(<\/span>"<\/span>\/users\/{user_id}<\/span>"<\/span>)<\/span><\/span>\ndef<\/span> <\/span>delete_user<\/span>(<\/span>user_id<\/span>: <\/span>int<\/span>,<\/span> <\/span>db<\/span>: <\/span>Session<\/span> <\/span>=<\/span> <\/span>Depends<\/span>(<\/span>get_db<\/span>)):<\/span><\/span>\n    <\/span>"""<\/span><\/span>\n    Deletes a user from the database by their unique user ID<\/span>.<\/span><\/span>\n    <\/span><\/span>\n    Parameters<\/span>:<\/span><\/span>\n        <\/span>user_id<\/span> (<\/span>int<\/span>): <\/span>The<\/span> <\/span>unique<\/span> <\/span>identifier<\/span> <\/span>of<\/span> <\/span>the<\/span> <\/span>user<\/span> <\/span>to<\/span> <\/span>be<\/span> <\/span>deleted<\/span>.<\/span><\/span>\n        <\/span>db<\/span> (<\/span>Session<\/span>): <\/span>The<\/span> <\/span>database<\/span> <\/span>session<\/span> <\/span>used<\/span> <\/span>to<\/span> <\/span>execute<\/span> <\/span>database<\/span> <\/span>operations<\/span>.<\/span> <\/span><\/span>\n                      <\/span>This<\/span> <\/span>session<\/span> <\/span>is<\/span> <\/span>automatically<\/span> <\/span>provided<\/span> <\/span>by<\/span> <\/span>FastAPI<\/span>'<\/span>s dependency injection<\/span>.<\/span><\/span>\n    <\/span><\/span>\n    Returns<\/span>:<\/span><\/span>\n        <\/span>A<\/span> <\/span>JSON<\/span> <\/span>object<\/span> <\/span>with<\/span> <\/span>a<\/span> <\/span>detail<\/span> <\/span>key<\/span> <\/span>indicating<\/span> <\/span>that<\/span> <\/span>the<\/span> <\/span>user<\/span> <\/span>has<\/span> <\/span>been<\/span> <\/span>successfully<\/span> <\/span>deleted<\/span>.<\/span><\/span>\n    <\/span><\/span>\n    Raises<\/span>:<\/span><\/span>\n        HTTPException<\/span>:<\/span> <\/span>A<\/span> <\/span>404<\/span> <\/span>status<\/span> <\/span>code<\/span> <\/span>is<\/span> <\/span>raised<\/span> <\/span>if<\/span> <\/span>no<\/span> <\/span>user<\/span> <\/span>with<\/span> <\/span>the<\/span> <\/span>given<\/span> <\/span>user_id<\/span> <\/span>exists<\/span> <\/span>in<\/span> <\/span>the<\/span> <\/span>database<\/span>.<\/span><\/span>\n    <\/span>"""<\/span><\/span>\n   <\/span> <\/span><\/span>\n    <\/span>db_user<\/span> <\/span>=<\/span> <\/span>db<\/span>.<\/span>query<\/span>(<\/span>User<\/span>)<\/span>.<\/span>filter<\/span>(<\/span>User<\/span>.<\/span>id<\/span> <\/span>==<\/span> <\/span>user_id<\/span>)<\/span>.<\/span>first<\/span>()<\/span><\/span>\n    <\/span>if<\/span> <\/span>not<\/span> db_user<\/span>:<\/span><\/span>\n        <\/span>raise<\/span> <\/span>HTTPException<\/span>(<\/span>status_code<\/span>=<\/span>404<\/span>,<\/span> <\/span>detail<\/span>=<\/span>"<\/span>User not found<\/span>"<\/span>)<\/span><\/span>\n    <\/span>db<\/span>.<\/span>delete<\/span>(<\/span>db_user<\/span>)<\/span><\/span>\n    <\/span>db<\/span>.<\/span>commit<\/span>()<\/span><\/span>\n    <\/span>return<\/span> <\/span>{<\/span>"<\/span>detail<\/span>"<\/span>:<\/span> <\/span>"<\/span>User deleted<\/span>"<\/span>}<\/span><\/span>\n<\/span><\/code><\/pre><\/div>

          Running Your Application<\/h3>

          Ensure all dependencies are installed and run your application with:<\/p>

          <\/circle><\/circle><\/circle><\/g><\/svg><\/span><\/path><\/path><\/svg><\/span>
          uvicorn<\/span> main<\/span>:<\/span>app<\/span> <\/span>--<\/span>reload<\/span><\/span><\/code><\/pre><\/div>

          Navigate to http:\/\/127.0.0.1:8000\/docs<\/code> in your browser to see the interactive API documentation provided by FastAPI, where you can test all these CRUD operations.<\/p>

          Conclusion<\/h3>

          This guide provided step-by-step examples for implementing CRUD operations in a FastAPI application with SQLAlchemy. By defining models, creating database sessions, and utilizing FastAPI’s dependency injection system, we demonstrated how to create, read, update, and delete resources in a database. These operations form the backbone of many web applications, providing a solid foundation for building robust APIs.<\/p>

          Leave a response to this article by providing your insights, comments, or requests for future articles.<\/strong> Share the articles with your friends and colleagues on social media.<\/strong><\/p>

          <\/p>

          <\/p>

          <\/p>","protected":false},"excerpt":{"rendered":"

          Diving into FastAPI for your project? Enhance it with database integration! This article provides a step-by-step guide, complete with examples, to help you seamlessly integrate a database with FastAPI, boosting your application’s functionality.<\/p>\n","protected":false},"author":2,"featured_media":405,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[116,17],"tags":[20,21,18,19,91,53,32,31],"class_list":["post-403","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-fast-api","category-programming","tag-google","tag-medium","tag-python","tag-python3","tag-database","tag-fastapi","tag-programmingtips","tag-pythondev"],"yoast_head":"\nDatabase Integration with FastAPI - 🌟Code with MrCoder7️⃣0️⃣1️⃣<\/title>\n<meta name=\"description\" content=\"Master database integration with FastAPI through our comprehensive guide. From setup to execution, learn how to seamlessly blend databases into your FastAPI projects with practical examples.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Database Integration with FastAPI - 🌟Code with MrCoder7️⃣0️⃣1️⃣\" \/>\n<meta property=\"og:description\" content=\"Master database integration with FastAPI through our comprehensive guide. From setup to execution, learn how to seamlessly blend databases into your FastAPI projects with practical examples.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/\" \/>\n<meta property=\"og:site_name\" content=\"🌟Code with MrCoder7️⃣0️⃣1️⃣\" \/>\n<meta property=\"article:published_time\" content=\"2024-03-06T16:35:47+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-03-15T11:25:25+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2240\" \/>\n\t<meta property=\"og:image:height\" content=\"1260\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"mr.coder\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"mr.coder\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/\"},\"author\":{\"name\":\"mr.coder\",\"@id\":\"https:\/\/www.mrcoder701.com\/#\/schema\/person\/ba1cd6b2ad26df384b1a655341eaef5d\"},\"headline\":\"Database Integration with FastAPI\",\"datePublished\":\"2024-03-06T16:35:47+00:00\",\"dateModified\":\"2024-03-15T11:25:25+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/\"},\"wordCount\":1221,\"commentCount\":1,\"publisher\":{\"@id\":\"https:\/\/www.mrcoder701.com\/#\/schema\/person\/ba1cd6b2ad26df384b1a655341eaef5d\"},\"image\":{\"@id\":\"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8.png\",\"keywords\":[\"#google\",\"#medium\",\"#python\",\"#python3\",\"database\",\"fastAPI\",\"ProgrammingTips\",\"PythonDev\"],\"articleSection\":[\"FastAPI\",\"Programming\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/\",\"url\":\"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/\",\"name\":\"Database Integration with FastAPI - 🌟Code with MrCoder7️⃣0️⃣1️⃣\",\"isPartOf\":{\"@id\":\"https:\/\/www.mrcoder701.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8.png\",\"datePublished\":\"2024-03-06T16:35:47+00:00\",\"dateModified\":\"2024-03-15T11:25:25+00:00\",\"description\":\"Master database integration with FastAPI through our comprehensive guide. From setup to execution, learn how to seamlessly blend databases into your FastAPI projects with practical examples.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/#primaryimage\",\"url\":\"https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8.png\",\"contentUrl\":\"https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8.png\",\"width\":2240,\"height\":1260},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.mrcoder701.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Database Integration with FastAPI\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.mrcoder701.com\/#website\",\"url\":\"https:\/\/www.mrcoder701.com\/\",\"name\":\"Blog With MrCoder701\",\"description\":\"Blog related to programming\",\"publisher\":{\"@id\":\"https:\/\/www.mrcoder701.com\/#\/schema\/person\/ba1cd6b2ad26df384b1a655341eaef5d\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.mrcoder701.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\/\/www.mrcoder701.com\/#\/schema\/person\/ba1cd6b2ad26df384b1a655341eaef5d\",\"name\":\"mr.coder\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.mrcoder701.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/06\/369B947D-A5EE-4B16-816A-5EE55D1DDF96_L0_001-10_6_2024-6-13-24-PM.png\",\"contentUrl\":\"https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/06\/369B947D-A5EE-4B16-816A-5EE55D1DDF96_L0_001-10_6_2024-6-13-24-PM.png\",\"width\":500,\"height\":500,\"caption\":\"mr.coder\"},\"logo\":{\"@id\":\"https:\/\/www.mrcoder701.com\/#\/schema\/person\/image\/\"},\"sameAs\":[\"https:\/\/mrcoder701.com\",\"https:\/\/www.instagram.com\/mr_coder_701\/\",\"https:\/\/www.youtube.com\/@mrcoder701\"],\"url\":\"https:\/\/www.mrcoder701.com\/author\/admin\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Database Integration with FastAPI - 🌟Code with MrCoder7️⃣0️⃣1️⃣","description":"Master database integration with FastAPI through our comprehensive guide. From setup to execution, learn how to seamlessly blend databases into your FastAPI projects with practical examples.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/","og_locale":"en_US","og_type":"article","og_title":"Database Integration with FastAPI - 🌟Code with MrCoder7️⃣0️⃣1️⃣","og_description":"Master database integration with FastAPI through our comprehensive guide. From setup to execution, learn how to seamlessly blend databases into your FastAPI projects with practical examples.","og_url":"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/","og_site_name":"🌟Code with MrCoder7️⃣0️⃣1️⃣","article_published_time":"2024-03-06T16:35:47+00:00","article_modified_time":"2024-03-15T11:25:25+00:00","og_image":[{"width":2240,"height":1260,"url":"https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8.png","type":"image\/png"}],"author":"mr.coder","twitter_card":"summary_large_image","twitter_misc":{"Written by":"mr.coder","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/#article","isPartOf":{"@id":"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/"},"author":{"name":"mr.coder","@id":"https:\/\/www.mrcoder701.com\/#\/schema\/person\/ba1cd6b2ad26df384b1a655341eaef5d"},"headline":"Database Integration with FastAPI","datePublished":"2024-03-06T16:35:47+00:00","dateModified":"2024-03-15T11:25:25+00:00","mainEntityOfPage":{"@id":"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/"},"wordCount":1221,"commentCount":1,"publisher":{"@id":"https:\/\/www.mrcoder701.com\/#\/schema\/person\/ba1cd6b2ad26df384b1a655341eaef5d"},"image":{"@id":"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/#primaryimage"},"thumbnailUrl":"https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8.png","keywords":["#google","#medium","#python","#python3","database","fastAPI","ProgrammingTips","PythonDev"],"articleSection":["FastAPI","Programming"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/","url":"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/","name":"Database Integration with FastAPI - 🌟Code with MrCoder7️⃣0️⃣1️⃣","isPartOf":{"@id":"https:\/\/www.mrcoder701.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/#primaryimage"},"image":{"@id":"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/#primaryimage"},"thumbnailUrl":"https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8.png","datePublished":"2024-03-06T16:35:47+00:00","dateModified":"2024-03-15T11:25:25+00:00","description":"Master database integration with FastAPI through our comprehensive guide. From setup to execution, learn how to seamlessly blend databases into your FastAPI projects with practical examples.","breadcrumb":{"@id":"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/#primaryimage","url":"https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8.png","contentUrl":"https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8.png","width":2240,"height":1260},{"@type":"BreadcrumbList","@id":"https:\/\/www.mrcoder701.com\/2024\/03\/06\/database-integration-fastapi-guide\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.mrcoder701.com\/"},{"@type":"ListItem","position":2,"name":"Database Integration with FastAPI"}]},{"@type":"WebSite","@id":"https:\/\/www.mrcoder701.com\/#website","url":"https:\/\/www.mrcoder701.com\/","name":"Blog With MrCoder701","description":"Blog related to programming","publisher":{"@id":"https:\/\/www.mrcoder701.com\/#\/schema\/person\/ba1cd6b2ad26df384b1a655341eaef5d"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.mrcoder701.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/www.mrcoder701.com\/#\/schema\/person\/ba1cd6b2ad26df384b1a655341eaef5d","name":"mr.coder","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.mrcoder701.com\/#\/schema\/person\/image\/","url":"https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/06\/369B947D-A5EE-4B16-816A-5EE55D1DDF96_L0_001-10_6_2024-6-13-24-PM.png","contentUrl":"https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/06\/369B947D-A5EE-4B16-816A-5EE55D1DDF96_L0_001-10_6_2024-6-13-24-PM.png","width":500,"height":500,"caption":"mr.coder"},"logo":{"@id":"https:\/\/www.mrcoder701.com\/#\/schema\/person\/image\/"},"sameAs":["https:\/\/mrcoder701.com","https:\/\/www.instagram.com\/mr_coder_701\/","https:\/\/www.youtube.com\/@mrcoder701"],"url":"https:\/\/www.mrcoder701.com\/author\/admin\/"}]}},"rttpg_featured_image_url":{"full":["https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8.png",2240,1260,false],"landscape":["https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8.png",2240,1260,false],"portraits":["https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8.png",2240,1260,false],"thumbnail":["https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8-150x150.png",150,150,true],"medium":["https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8-300x169.png",300,169,true],"large":["https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8-1024x576.png",1024,576,true],"1536x1536":["https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8-1536x864.png",1536,864,true],"2048x2048":["https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8-2048x1152.png",2048,1152,true],"woocommerce_thumbnail":["https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8-300x300.png",300,300,true],"woocommerce_single":["https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8.png",600,338,false],"woocommerce_gallery_thumbnail":["https:\/\/www.mrcoder701.com\/wp-content\/uploads\/2024\/03\/Wardiere-In.-8-150x150.png",150,150,true]},"rttpg_author":{"display_name":"mr.coder","author_link":"https:\/\/www.mrcoder701.com\/author\/admin\/"},"rttpg_comment":1,"rttpg_category":"<a href=\"https:\/\/www.mrcoder701.com\/category\/fast-api\/\" rel=\"category tag\">FastAPI<\/a> <a href=\"https:\/\/www.mrcoder701.com\/category\/programming\/\" rel=\"category tag\">Programming<\/a>","rttpg_excerpt":"Diving into FastAPI for your project? Enhance it with database integration! This article provides a step-by-step guide, complete with examples, to help you seamlessly integrate a database with FastAPI, boosting your application's functionality.","_links":{"self":[{"href":"https:\/\/www.mrcoder701.com\/wp-json\/wp\/v2\/posts\/403","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.mrcoder701.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.mrcoder701.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.mrcoder701.com\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.mrcoder701.com\/wp-json\/wp\/v2\/comments?post=403"}],"version-history":[{"count":2,"href":"https:\/\/www.mrcoder701.com\/wp-json\/wp\/v2\/posts\/403\/revisions"}],"predecessor-version":[{"id":406,"href":"https:\/\/www.mrcoder701.com\/wp-json\/wp\/v2\/posts\/403\/revisions\/406"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.mrcoder701.com\/wp-json\/wp\/v2\/media\/405"}],"wp:attachment":[{"href":"https:\/\/www.mrcoder701.com\/wp-json\/wp\/v2\/media?parent=403"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.mrcoder701.com\/wp-json\/wp\/v2\/categories?post=403"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.mrcoder701.com\/wp-json\/wp\/v2\/tags?post=403"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}