├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── database.py ├── main.py ├── models.py ├── requirements.txt ├── schemas.py └── services.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Francis Ali 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # fastapi-postgres-docker -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sixfwa/fastapi-postgres-docker/7cb63f89dff48d9fef66c053b775053ec3161f3d/__init__.py -------------------------------------------------------------------------------- /database.py: -------------------------------------------------------------------------------- 1 | import sqlalchemy as _sql 2 | import sqlalchemy.ext.declarative as _declarative 3 | import sqlalchemy.orm as _orm 4 | 5 | DATABASE_URL = "postgresql://myuser:password@localhost/fastapi_database" 6 | 7 | engine = _sql.create_engine(DATABASE_URL) 8 | 9 | SessionLocal = _orm.sessionmaker(autocommit=False, autoflush=False, bind=engine) 10 | 11 | Base = _declarative.declarative_base() 12 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | from typing import TYPE_CHECKING, List 2 | import fastapi as _fastapi 3 | import sqlalchemy.orm as _orm 4 | 5 | import schemas as _schemas 6 | import services as _services 7 | 8 | if TYPE_CHECKING: 9 | from sqlalchemy.orm import Session 10 | 11 | app = _fastapi.FastAPI() 12 | 13 | 14 | @app.post("/api/contacts/", response_model=_schemas.Contact) 15 | async def create_contact( 16 | contact: _schemas.CreateContact, 17 | db: _orm.Session = _fastapi.Depends(_services.get_db), 18 | ): 19 | return await _services.create_contact(contact=contact, db=db) 20 | 21 | 22 | @app.get("/api/contacts/", response_model=List[_schemas.Contact]) 23 | async def get_contacts(db: _orm.Session = _fastapi.Depends(_services.get_db)): 24 | return await _services.get_all_contacts(db=db) 25 | 26 | 27 | @app.get("/api/contacts/{contact_id}/", response_model=_schemas.Contact) 28 | async def get_contact( 29 | contact_id: int, db: _orm.Session = _fastapi.Depends(_services.get_db) 30 | ): 31 | contact = await _services.get_contact(db=db, contact_id=contact_id) 32 | if contact is None: 33 | raise _fastapi.HTTPException(status_code=404, detail="Contact does not exist") 34 | 35 | return contact 36 | 37 | 38 | @app.delete("/api/contacts/{contact_id}/") 39 | async def delete_contact( 40 | contact_id: int, db: _orm.Session = _fastapi.Depends(_services.get_db) 41 | ): 42 | contact = await _services.get_contact(db=db, contact_id=contact_id) 43 | if contact is None: 44 | raise _fastapi.HTTPException(status_code=404, detail="Contact does not exist") 45 | 46 | await _services.delete_contact(contact, db=db) 47 | 48 | return "successfully deleted the user" 49 | 50 | 51 | @app.put("/api/contacts/{contact_id}/", response_model=_schemas.Contact) 52 | async def update_contact( 53 | contact_id: int, 54 | contact_data: _schemas.CreateContact, 55 | db: _orm.Session = _fastapi.Depends(_services.get_db), 56 | ): 57 | contact = await _services.get_contact(db=db, contact_id=contact_id) 58 | if contact is None: 59 | raise _fastapi.HTTPException(status_code=404, detail="Contact does not exist") 60 | 61 | return await _services.update_contact( 62 | contact_data=contact_data, contact=contact, db=db 63 | ) 64 | -------------------------------------------------------------------------------- /models.py: -------------------------------------------------------------------------------- 1 | import datetime as _dt 2 | import sqlalchemy as _sql 3 | 4 | import database as _database 5 | 6 | 7 | class Contact(_database.Base): 8 | __tablename__ = "contacts" 9 | id = _sql.Column(_sql.Integer, primary_key=True, index=True) 10 | first_name = _sql.Column(_sql.String, index=True) 11 | last_name = _sql.Column(_sql.String, index=True) 12 | email = _sql.Column(_sql.String, index=True, unique=True) 13 | phone_number = _sql.Column(_sql.String, index=True, unique=True) 14 | date_created = _sql.Column(_sql.DateTime, default=_dt.datetime.utcnow) 15 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | anyio==3.3.4 2 | asgiref==3.4.1 3 | black==21.9b0 4 | certifi==2021.10.8 5 | charset-normalizer==2.0.7 6 | click==8.0.3 7 | dnspython==2.1.0 8 | email-validator==1.1.3 9 | fastapi==0.70.0 10 | h11==0.12.0 11 | httptools==0.2.0 12 | idna==3.3 13 | itsdangerous==2.0.1 14 | Jinja2==3.0.2 15 | MarkupSafe==2.0.1 16 | mypy-extensions==0.4.3 17 | orjson==3.6.4 18 | pathspec==0.9.0 19 | platformdirs==2.4.0 20 | psycopg2-binary==2.9.1 21 | pydantic==1.8.2 22 | python-dotenv==0.19.1 23 | python-multipart==0.0.5 24 | PyYAML==5.4.1 25 | regex==2021.10.23 26 | requests==2.26.0 27 | six==1.16.0 28 | sniffio==1.2.0 29 | SQLAlchemy==1.4.26 30 | starlette==0.16.0 31 | tomli==1.2.2 32 | typing-extensions==3.10.0.2 33 | ujson==4.2.0 34 | urllib3==1.26.7 35 | uvicorn==0.15.0 36 | uvloop==0.16.0 37 | watchgod==0.7 38 | websockets==10.0 39 | -------------------------------------------------------------------------------- /schemas.py: -------------------------------------------------------------------------------- 1 | import datetime as _dt 2 | import pydantic as _pydantic 3 | 4 | 5 | class _BaseContact(_pydantic.BaseModel): 6 | first_name: str 7 | last_name: str 8 | email: str 9 | phone_number: str 10 | 11 | 12 | class Contact(_BaseContact): 13 | id: int 14 | date_created: _dt.datetime 15 | 16 | class Config: 17 | orm_mode = True 18 | 19 | 20 | class CreateContact(_BaseContact): 21 | pass 22 | -------------------------------------------------------------------------------- /services.py: -------------------------------------------------------------------------------- 1 | from typing import TYPE_CHECKING, List 2 | 3 | import database as _database 4 | import models as _models 5 | import schemas as _schemas 6 | 7 | if TYPE_CHECKING: 8 | from sqlalchemy.orm import Session 9 | 10 | 11 | def _add_tables(): 12 | return _database.Base.metadata.create_all(bind=_database.engine) 13 | 14 | 15 | def get_db(): 16 | db = _database.SessionLocal() 17 | try: 18 | yield db 19 | finally: 20 | db.close() 21 | 22 | 23 | async def create_contact( 24 | contact: _schemas.CreateContact, db: "Session" 25 | ) -> _schemas.Contact: 26 | contact = _models.Contact(**contact.dict()) 27 | db.add(contact) 28 | db.commit() 29 | db.refresh(contact) 30 | return _schemas.Contact.from_orm(contact) 31 | 32 | 33 | async def get_all_contacts(db: "Session") -> List[_schemas.Contact]: 34 | contacts = db.query(_models.Contact).all() 35 | return list(map(_schemas.Contact.from_orm, contacts)) 36 | 37 | 38 | async def get_contact(contact_id: int, db: "Session"): 39 | contact = db.query(_models.Contact).filter(_models.Contact.id == contact_id).first() 40 | return contact 41 | 42 | 43 | async def delete_contact(contact: _models.Contact, db: "Session"): 44 | db.delete(contact) 45 | db.commit() 46 | 47 | 48 | async def update_contact( 49 | contact_data: _schemas.CreateContact, contact: _models.Contact, db: "Session" 50 | ) -> _schemas.Contact: 51 | contact.first_name = contact_data.first_name 52 | contact.last_name = contact_data.last_name 53 | contact.email = contact_data.email 54 | contact.phone_number = contact_data.phone_number 55 | 56 | db.commit() 57 | db.refresh(contact) 58 | 59 | return _schemas.Contact.from_orm(contact) 60 | --------------------------------------------------------------------------------