Skip to content
This repository was archived by the owner on Aug 19, 2024. It is now read-only.

Commit 9ed54d5

Browse files
committed
initial commit
0 parents  commit 9ed54d5

File tree

7 files changed

+193
-0
lines changed

7 files changed

+193
-0
lines changed

.gitignore

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
env
2+
__pycache__
3+
venv
4+
*.db
5+
*.sqlite3

README.md

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# Build a REST API with FastAPI, PostgreSQL and SQLAlchemy
2+
FastAPI is a Python framework and set of tools that allow developers to invoke commonly used functions using a REST interface.
3+
4+
SQLAlchemy is a package that makes it easier for Python programs to communicate with databases. Most of the time, this library is used as an Object Relational Mapper (ORM) tool, which automatically converts function calls to SQL queries and translates Python classes to tables on relational databases.
5+
6+
Many web, mobile, geospatial, and analytics applications use PostgreSQL as their primary data storage or data warehouse.
7+
8+
This is code I wrote for the [video](https://youtu.be/2g1ZjA6zHRo)
9+
10+
## How to run the REST API
11+
Get this project from Github
12+
```
13+
git clone https://github.com/jod35/Build-a-fastapi-and-postgreSQL-API-with-SQLAlchemy
14+
15+
```
16+
17+
18+
19+
### Setting up the database
20+
21+
* Install PostgreSQL and create your user and database
22+
23+
* Change this line in ` database.py ` to
24+
25+
```
26+
engine=create_engine("postgresql://{YOUR_DATABASE_USER}:{YOUR_DATABASE_PASSWORD}@localhost/{YOUR_DATABASE_NAME}",
27+
echo=True
28+
)
29+
```
30+
31+
### Create a virtual environment
32+
This can be done with
33+
``` python -m venv env ```
34+
35+
activate the virtual environment with
36+
37+
```
38+
env/bin/activate
39+
```
40+
41+
or
42+
43+
```
44+
env\Scripts\activate
45+
```
46+
47+
48+
49+
### Install the requirements
50+
51+
```
52+
pip install -r requirements.txt
53+
```
54+
55+
### Create the database
56+
``` python create_db.py ```
57+
58+
## Run the API
59+
``` python main.py ```
60+
61+
## Author
62+
[Ssali Jonathan](https://github.com/jod35)

create_db.py

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
from database import Base,engine
2+
from models import Item
3+
4+
print("Creating database ....")
5+
6+
Base.metadata.create_all(engine)

database.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from sqlalchemy.orm import declarative_base
2+
from sqlalchemy import create_engine
3+
from sqlalchemy.orm import sessionmaker
4+
5+
engine=create_engine("postgresql://{YOUR_DATABASE_USER}:{YOUR_DATABASE_PASSWORD}@localhost/{YOUR_DATABASE_NAME}",
6+
echo=True
7+
)
8+
9+
Base=declarative_base()
10+
11+
SessionLocal=sessionmaker(bind=engine)

main.py

+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
from os import stat
2+
from fastapi import FastAPI,status,HTTPException
3+
from pydantic import BaseModel
4+
from typing import Optional,List
5+
from database import SessionLocal
6+
import models
7+
8+
app=FastAPI()
9+
10+
class Item(BaseModel): #serializer
11+
id:int
12+
name:str
13+
description:str
14+
price:int
15+
on_offer:bool
16+
17+
class Config:
18+
orm_mode=True
19+
20+
21+
db=SessionLocal()
22+
23+
@app.get('/items',response_model=List[Item],status_code=200)
24+
def get_all_items():
25+
items=db.query(models.Item).all()
26+
27+
return items
28+
29+
@app.get('/item/{item_id}',response_model=Item,status_code=status.HTTP_200_OK)
30+
def get_an_item(item_id:int):
31+
item=db.query(models.Item).filter(models.Item.id==item_id).first()
32+
return item
33+
34+
@app.post('/items',response_model=Item,
35+
status_code=status.HTTP_201_CREATED)
36+
def create_an_item(item:Item):
37+
db_item=db.query(models.Item).filter(models.Item.name==item.name).first()
38+
39+
if db_item is not None:
40+
raise HTTPException(status_code=400,detail="Item already exists")
41+
42+
43+
44+
new_item=models.Item(
45+
name=item.name,
46+
price=item.price,
47+
description=item.description,
48+
on_offer=item.on_offer
49+
)
50+
51+
52+
53+
54+
db.add(new_item)
55+
db.commit()
56+
57+
return new_item
58+
59+
@app.put('/item/{item_id}',response_model=Item,status_code=status.HTTP_200_OK)
60+
def update_an_item(item_id:int,item:Item):
61+
item_to_update=db.query(models.Item).filter(models.Item.id==item_id).first()
62+
item_to_update.name=item.name
63+
item_to_update.price=item.price
64+
item_to_update.description=item.description
65+
item_to_update.on_offer=item.on_offer
66+
67+
db.commit()
68+
69+
return item_to_update
70+
71+
@app.delete('/item/{item_id}')
72+
def delete_item(item_id:int):
73+
item_to_delete=db.query(models.Item).filter(models.Item.id==item_id).first()
74+
75+
if item_to_delete is None:
76+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail="Resource Not Found")
77+
78+
db.delete(item_to_delete)
79+
db.commit()
80+
81+
return item_to_delete

models.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from sqlalchemy.sql.expression import null
2+
from database import Base
3+
from sqlalchemy import String,Boolean,Integer,Column,Text
4+
5+
6+
class Item(Base):
7+
__tablename__='items'
8+
id=Column(Integer,primary_key=True)
9+
name=Column(String(255),nullable=False,unique=True)
10+
description=Column(Text)
11+
price=Column(Integer,nullable=False)
12+
on_offer=Column(Boolean,default=False)
13+
14+
15+
def __repr__(self):
16+
return f"<Item name={self.name} price={self.price}>"

requirements.txt

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
asgiref==3.3.4
2+
click==8.0.1
3+
colorama==0.4.4
4+
fastapi==0.65.2
5+
greenlet==1.1.0
6+
h11==0.12.0
7+
psycopg2-binary==2.9.1
8+
pydantic==1.8.2
9+
SQLAlchemy==1.4.19
10+
starlette==0.14.2
11+
typing-extensions==3.10.0.0
12+
uvicorn==0.14.0

0 commit comments

Comments
 (0)