0% found this document useful (0 votes)
47 views

PDF FastAPI Slides

Uploaded by

ranggaaryo FR
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

PDF FastAPI Slides

Uploaded by

ranggaaryo FR
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 200

INSTALLING PYTHON

LET’S CODE TOGETHER © CODINGWITHROBY


CHECK IF YOU ALREADY HAVE PYTHON 3 INSTALLED

Inside your “terminal” for Mac, or


“command prompt” for windows.
Type “python –-version”

LET’S CODE TOGETHER © CODINGWITHROBY


PYTHON INTEGRATED DEVELOPMENT
ENVIRONMENT

LET’S CODE TOGETHER © CODINGWITHROBY


WHAT ARE IDES?

IDEs are simply a source code editor. This means an IDE


will help and assist in writing software!
Many of them have terminals and other useful build
automation tools embedded within.
IDEs have debugger tools that allow you to dive deep
within the code to find bugs and create solutions

LET’S CODE TOGETHER © CODINGWITHROBY


WHY DO DEVELOPERS USE IDES?

IDEs allow developers to begin work quickly and efficiently


due to all the tools that come out of the box
IDEs also parse all code, and helps find bugs before they
are committed by human error
The GUIs of IDEs is created with one goal in mind, help
developers be efficient.

LET’S CODE TOGETHER © CODINGWITHROBY


SETTING UP A PYTHON IDE

LET’S CODE TOGETHER © CODINGWITHROBY


PYTHON VIRTUAL ENVIRONMENTS

LET’S CODE TOGETHER © CODINGWITHROBY


PYTHON VIRTUAL ENVIRONMENT

A virtual environment is a Python environment that is


isolated from those in other Python environments.

FastAPI A.I. Internet of Things

LET’S CODE TOGETHER © CODINGWITHROBY


HOW ARE WE GOING TO INSTALL THE DEPENDENCIES?

Pip: Pip is the Python package manager.


Pip is used to install and update packages.
You will want to make sure you have the latest version of pip
installed

Unix/Mac OS Windows

LET’S CODE TOGETHER © CODINGWITHROBY


HOW WILL WE BE SETTING UP THE VIRTUAL ENVIRONMENT

I started by creating a brand-new folder / directory called


“FastAPI”
Within our pip we will be checking what dependencies we
already have installed.
Installing Virtual Env if it is not installed.
Creating a new FastAPI environment as a virtual environment
Activating our virtual environment
Lastly, installing FastAPI to our virtual environment
LET’S CODE TOGETHER © CODINGWITHROBY
SWAGGER, OPENAPI, REQUEST METHODS &
STATUS CODES

LET’S CODE TOGETHER © CODINGWITHROBY


OPENAPI SPECIFICATION (OAS):

OpenAPI Document Defines:


Schema
Data Format
Data Type
Path
Object
And much more

LET’S CODE TOGETHER © CODINGWITHROBY


VIEW OPENAPI SCHEMA

FastAPI generates the


OpenAPI schema so you can
view
http://127.0.0.1:8000/openapi.json
Helps the developer create
RESTful APIs based on
standards so individuals can
use the APIs easily

LET’S CODE TOGETHER © CODINGWITHROBY


SWAGGER-UI
http://127.0.0.1:8000/docs

LET’S CODE TOGETHER © CODINGWITHROBY


FASTAPI USES HTTP REQUEST METHODS

CRUD
GET Read method that retrieves data

POST Create method, to submit data

PUT Update the entire resource

PATCH Update part of the resource

DELETE Delete the resource

LET’S CODE TOGETHER © CODINGWITHROBY


FASTAPI REQUEST METHODS (CONT)

TRACE Performs a message loop-back to the


target
OPTIONS Describes communication options to the
target
CONNECT Creates a tunnel to the server, based on
the target resource

LET’S CODE TOGETHER © CODINGWITHROBY


FASTAPI RESPONSE STATUS CODE

1xx Informational Response: Request


processing
2xx Success: Request successfully complete

3xx Redirection: Further action must be


complete
4xx Client Errors: An error was caused by the
request from the client
5xx Server Errors: An error has occurred on
the server
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
Introduction COURSE CONTENT!

Python & IDE Swagger & HTTP Forms


Installation

GET, POST, PUT,


Project / App 1 Project / App 3
DELETE

VirtualENV Project / App 2 Database & ORM

Classes, Handling
First RESTful API Authentication JWT
Errors

LET’S CODE TOGETHER © CODINGWITHROBY


Routing Full Stack

Alembic Deployment

LET’S CODE TOGETHER © CODINGWITHROBY


HOW TO GET THE MOST OUT OF THE
COURSE!

Watch all the Videos Control the speed of videos to


your pace

Take the Exercises Pause videos to take exercises


before seeing solutions

Search & Practice Advance on your own and search


for additional information

Ask Questions
Ask in Q&A section!

LET’S CODE TOGETHER © CODINGWITHROBY


FASTAPI OVERVIEW

LET’S CODE TOGETHER © CODINGWITHROBY


WHAT IS FASTAPI?

FastAPI is a Python web-framework for building modern


APIs
Fast (Performance)
Fast (Development)
Key Notes:
Few Bugs
Quick & Easy
Robust
Standards

LET’S CODE TOGETHER © CODINGWITHROBY


WHAT DOES THIS ALL MEAN FOR YOU?

FastAPI is a web-framework for building modern RESTful APIs

Official
documentation

https://fastapi.tiangolo.com/

LET’S CODE TOGETHER © CODINGWITHROBY


WHERE DOES FASTAPI FIT WITHIN AN APPLICATION ARCHITECTURE?

Full
RestStack Application
API for data
Web Page Server

Handles all business logic for the application

LET’S CODE TOGETHER © CODINGWITHROBY


WHO HAS USED FASTAPI?

Netflix Uber Microsoft

LET’S CODE TOGETHER © CODINGWITHROBY


CAN’T I JUST WRITE EVERYTHING MYSELF?

FAQ: Why do I need a web framework?


You may be able to write everything yourself, but why reinvent
the wheel?
Web-frameworks allow a simplified way for rapid
development.
Includes many years of development, which allows you to
have a secure and fast application! ☺

LET’S CODE TOGETHER © CODINGWITHROBY


Books Project
What will we be creating?

• Creating and enhancing books to learn the basics of FastAPI


BOOKS = {
{‘title’: ‘Title One’, ‘author’: ‘Author One’, ‘category’: ‘science’},
{‘title’: ‘Title Two’, ‘author’: ‘Author Two’, ‘category’: ‘science’},
{‘title’: ‘Title Three’, ‘author’: ‘Author Three’, ‘category’:
‘history’},
{‘title’: ‘Title Four’, ‘author’: ‘Author Four’, ‘category’: ‘math’},
{‘title’: ‘Title Five’, ‘author’: ‘Author Five’, ‘category’: ‘math’},

CRUD Operations
Create Read Update Delete

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Request and Response

HTTP Request Methods

Web Page Server

Response

CRUD Operations

Create Read Update Delete

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
HTTP Request Methods
CRUD HTTP Request Methods

Create POST

Read GET

Update PUT

Delete DELETE

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
GET HTTP Request Method
Creating a FastAPI application
File: books.py

from fastapi import FastAPI

app = FastAPI()

@app.get(“/api-endpoint”)
async def first_api():
return {‘message’: ‘Hello Eric!’}

Lets dive into the first function

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Dive in
API Endpoint:

@app.get(“/api-endpoint”)
async def first_api():
return {‘message’: ‘Hello Eric!’}
Read

Get URL : 127.0.0.1:8000/api-endpoint


Response:
{
“message”: “Hello Eric!”
}

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Start FastAPI Application
API Endpoint:

@app.get(“/api-endpoint”)
async def first_api():
Read return {‘message’: ‘Hello Eric!’}

Get Run FastAPI application:


ericroby@Erics-MacBook-Pro ~% uvicorn books:app --reload

URL : 127.0.0.1:8000

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Change Endpoint for Books

Read @app.get(“/api-endpoint”)
@app.get(“/books”)
async
async def
def read_all_books():
read_all_books():
return
return BOOKS
BOOKS

Get

URL :URL
127.0.0.1:8000/api-endpoint
: 127.0.0.1:8000/books

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Path Parameters
What are Path Parameters

• Path Parameters are request parameters that have been attached to the
URL

• Path Parameters are usually de ned as a way to nd information based


on location

• Think of a computer le system:

• You can identify the speci c resources based on the le you are in

/Users/codingwithroby/Documents/python/fastapi/section1

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
fi
fi
fi
fi
Path Parameters
REQUEST:
URL : 127.0.0.1:8000/books
Read
@app.get(“/books”)
async def read_all_books():
return BOOKS
Get

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Path Parameters
REQUEST:
URL : 127.0.0.1:8000/books/book_one
Read
@app.get(“/books /{dynamic_param}”)
async def read_all_books(dynamic_param):
return {‘dynamic_param’: dynamic_param}

Get

RESPONSE:
{
“dynamic_param”: “book_one”
}

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Order Matters with Path Parameters
REQUEST:
URL : 127.0.0.1:8000/books/mybook
Read
@app.get(“/books/mybook”)
@app.get(“/books/{dynamic_param}”)
async def read_all_books():
read_all_books(dynamic_param):
return {‘book_title’:
{‘dynamic_param’:
’Mydynamic_param}
Favorite Book’}

Get @app.get(“/books/{dynamic_param}”)
@app.get(“/books/mybook”)
async def read_all_books(dynamic_param):
read_all_books():
return {‘dynamic_param’:
{‘book_title’: ’Mydynamic_param}
Favorite Book’}

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Path Parameters
Read
REQUEST:
URL : 127.0.0.1:8000/books/title%20four = title four

Get
@app.get(“/books/{book_title}”)
async def read_book(book_title: str):
for book in BOOKS:
if book.get(‘title’).casefold() ==
book_title.casefold():

RESPONSE:
{
“title”: “Title Four”,
“author”: “Author Four”,
“category”: “math”
}

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Query Parameters
What are Query Parameters

• Query Parameters are request parameters that have been attached after
a “?”

• Query Parameters have name=value pairs

• Example:

• 127.0.0.1:8000/books/?category=math

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Query Parameters
REQUEST:
URL : 127.0.0.1:8000/books/?category=science

@app.get(“/books/”)
async def read_category_by_query(category: str):
books_to_return = []
for book in BOOKS:
if book.get(‘category’).casefold() == category.casefold():
books_to_return.append(book)

return books_to_return

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Query Parameters
REQUEST:
URL : 127.0.0.1:8000/books/author%20four/?category=science

@app.get(“/books/{book_author}/”)
async def read_category_by_query(book_author: str, category: str):
books_to_return = []
for book in BOOKS:
if book.get(‘author’).casefold() == book_author.casefold() and
book.get(‘category’).casefold() == category.casefold():
books_to_return.append(book)

return books_to_return

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
POST HTTP Request Method
What is the POST Request Method

• Used to create data

• POST can have a body that has additional information that GET does
not have

• Example of Body:

{“title”:”Title Seven”, “author”:”Author Two”, “category”:

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
POST Request Method
REQUEST:
URL : 127.0.0.1:8000/books/create_book
Create
@app.post(“/books/create_book”)
async def create_book(new_book=Body()):
BOOKS.append(new_book)
Post

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
PUT HTTP Request Method
What is the PUT Request Method

• Used to update data

• PUT can have a body that has additional information (like POST) that
GET does not have

• Example of Body:

{“title”:”Title Six”, “author”:”Author Two”, “category”:

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
PUT Request Method
Update
REQUEST:
Put URL : 127.0.0.1:8000/books/update_book

@app.put(“/books/update_book”)
async def update_book(updated_book=Body()):
for i in range(len(BOOKS)):
if BOOKS[i].get(‘title’).casefold() == updated_book.get(‘title’).casefold():
BOOKS[i] = updated_book

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
DELETE HTTP Request Method
What is the DELETE Request Method
• Used to delete data

Delete

REQUEST:
Delete URL : 127.0.0.1:8000/books/delete_book/{book_title}

@app.delete(“/books/delete_book/{book_title}”)
async def delete_book(book_title: str):
for i in range(len(BOOKS)):
if BOOKS[i].get(‘title’).casefold() == book_title.casefold():
BOOKS.pop(i)
break

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Books 2 Project
Project 2

• Project two will still be focused on creating Book API Endpoints

• Continued Education includes:

• GET, POST, PUT, DELETE Request Methods

• New Information will include:

• Data Validation, Exception Handling, Status Codes, Swagger


Con guration, Python Request Objects

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
Creating a new books project
• We will create a new class called Book

• We will be using these books throughout this


project:
class Book:
id: int
title: str
author: str
description: str
rating: int

def __init__ (self, id, title, author, description, rating):


self.id = id
self.title = title
self.author = author
self.description = description
self.rating = rating

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
HTTP Request Methods
CRUD HTTP Request Methods

Create POST

Read GET

Update PUT

Delete DELETE

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Pydantics
What is Pydantics

• Python library that is used for data modeling, data parsing and has
ef cient error handling.

• Pydantics is commonly used as a resource for data validation and how to


handle data coming to our FastAPI application.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
We will be implementing Pydantics
• Create a different request model for data validation

• Field data validation on each variable / element

class BookRequest(BaseModel):
id: int
title: str = Field(min_length=3)
author: str = Field(min_length=1)
description: str = Field(min_length=1, max_length=100)
rating: int = Field(gt=0, lt=5)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
BookRequest and Book Conversion
• We will convert the Pydantics Request into a Book

• Here is an example within an upcoming Post Request Method

@app.post(“/create-book”)
async def create_book(book_request: BookRequest):
new_book = Book(**book_request.dict())
BOOKS.append(new_book)

** operator will pass the key/value from BookRequest() into the Book() constructor

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Status Codes
What are Status Codes?

• An HTTP Status Code is used to help the Client (the user or system
submitting data to the server) to understand what happened on the
server side application.

• Status Codes are international standards on how a Client/Server should


handle the result of a request.

• It allows everyone who sends a request to know if their submission was


successful or not.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Status Codes:
1xx Information Response: Request Processing.

2xx Success: Request Successfully complete

3xx Redirection: Further action must be complete

4xx Client Errors: An error was caused by the client.

5xx Server Errors: An error occurred on the server.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
2xx Successful Status Codes:
Standard Response for a Successful Request. Commonly
200: OK used for successful Get requests when data is being
returned.

201: The request has been successful, creating a new resource.


Used when a POST creates an entity.

204: No The request has been successful, did not create an entity
nor return anything. Commonly used with PUT requests.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
4xx Client Errors Status Codes:
400: Bad Cannot process request due to client error. Commonly used
for invalid request methods.

Client does not have valid authentication for target


401: Unauthorized
resource

404: Not The clients requested resource can not be found

422: Unprocessable Semantic Errors in Client Request


Entity

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
5xx Server Status Codes:

Generic Error Message, when an unexpected issue on the


500: Internal Server
server happened.
Error

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Project 3
Project 3

• Project three we will be switching our focus to TODOS instead of BOOKS

• New Information will include:

• Full SQL Database

• Authentication Continued learning from


• Authorization other projects

• Hashing Passwords

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Creating a Todo Table
• We will create new Todo Table Models for our application

• We will be using these Todos to save records throughout this project

Authorization & Authentication Retrieving the user and saving Todos

Database

Web Page Server

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
SQL Database Introduction
What is a database?
• Organized collection of structured information of data, which is stored in
a computer system.

• The data can be easily accessed

• The data can be modi ed


What is Data?
• The data can be controlled and organized

• Many databases use a structured query language (SQL) to modify and


write data

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
What is a database?
• Data can be related to just about any object.

• For example, a user on an application may have:

• Name

• Age

• Email
All of this is Data
• Password

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is a database?
• A database is a collection of data

• Since data, on its own, is just data. A database allows management of this
data

• Databases are organized in how data can be retrieved, stored and


modi ed

• There are many types of Database Management Systems (DBMS)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
What is a SQL?
• Pronounced either as S-Q-L or “See Quel”

• Standard language for dealing with relational databases

• SQL can be used to do different things with database records:

• Create

• Read

• Update

• Delete

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
JSON WEB TOKEN (JWT) OVERVIEW

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A JSON WEB TOKEN?

JSON Web Token is a self-contained way to securely


transmit data and information between two parties using a
JSON Object.
JSON Web Tokens can be trusted because each JWT can
be digitally signed, which in return allows the server to
know if the JWT has been changed at all
JWT should be used when dealing with authorization
JWT is a great way for information to be exchanged
between the server and client

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JSON WEB TOKEN STRUCTURE

A JSON Web Token is created of three separate parts separated


by dots ( . ) which include:
Header : (a)
Payload : (b)
Signature : (c)

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JWT HEADER

A JWT header usually consist of two


parts:
(alg) The algorithm for signing
“typ” The specific type of token
The JWT header is then encoded using
Base64 to create the first part of the JWT (a)

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JWT PAYLOAD

A JWT Payload consists of the data.


The Payloads data contains claims, and
there are three different types of claims.
Registered
Public
Private
The JWT Payload is then encoded using
Base64 to create the second part of the JWT
(b)

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JWT SIGNATURE

A JWT Signature is created by using the


algorithm in the header to hash out the
encoded header, encoded payload with a
secret.
The secret can be anything, but is saved
somewhere on the server that the client does
not have access to
The signature is the third and final part of a
JWT (c)

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JWT EXAMPLE

JWT Header JWT Payload JWT Signature

JSON Web Token

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
https://jwt.io

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
https://jwt.io

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JWT PRACTICAL USE CASE

78…
t h 5
y
e7a
App 1

e7a
yth
578

App 2

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
PRODUCTION DATABASE INTRODUCTION

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
PRODUCTION DATABASE

This section will go over installing a production


relational database for your application!
Before jumping in, lets take
The two DBMS applications we will be going over is
about
MySQL the difference between
and PostgreSQL.
Both DBMS systems are used widely through out
SQLite
enterprise andandproduction
applications, you cannot go wrongDBMS
with
either one

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
PRODUCTION DBMS VS SQLITE3

SQLite3 strives to provide local data storage for


individual applications and devices.
SQLite3 emphasizes economy, efficiency and simplicity.
For most small / medium applications, SQLite3 will
works perfectly.
SQLite3 focuses on different concepts than a
production Database Management System.

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
PRODUCTION DBMS VS SQLITE3

MySQL & PostgreSQL focuses on a big difference


compared to SQLite3.
These production DBMS focuses on scalability,
concurrency and control.
If you application is going to have 10s of thousands of
users, it may be wise to switch to a production DBMS
If you application is only you, and a few others, SQLite3
will work great!

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
PRODUCTION DBMS KEY NOTES:

SQLite3 runs in-memory, which allows development of a


SQLite3 data to be easy, as it is part of your application!
Production DBMS run on their own server and port. Which
means you need to make sure the database is running, and
have authentication linking to the DBMS
(SQLite3) For deployment you can deploy a SQLite3 database
along with the application
(Prod DBMS) For deployment you will need to also deploy the
database separate from the application

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
OVERVIEW OF SECTION (FOR BOTH MYSQL & POSTGRESQL)

We will install the production DBMS


Setup the tables and data within the production DBMS
Connect the production DBMS to our application
Push data from application to our production DBMS!

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
BASIC SQL QUERIES

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
INSERTING DATABASE TABLE (TODOS)

Id (PK) title description priority complete owner (FK)

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
DELET THIS IS THE USERS TABLE
Id (PK) email username first_name last_name hashed_passwor is_active
d

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
DELET THIS IS THE USERS TABLE
Id (PK) email username first_name last_name hashed_passwor is_active
d
1 codingwithroby codingwithroby Eric Roby 123abcEqw!.. 1
@gmail.com
2 exampleuser12 exampleuser Example User Gjjjd!2!.. 1
@example.com

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
INSERTING DATABASE TABLE (TODOS)

INSERT INTO todos (title,


description, priority, complete)

VALUES (‘Go to store’, ‘To pick up


eggs’ 4, False);

Id (PK) title description priority complete

1 Go to store To pick up eggs 4 0

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
INSERTING DATABASE TABLE (TODOS)

INSERT INTO todos (title,


description, priority, complete)

VALUES (‘Haircut’, ‘Need to get


length 1mm’ 3, False);

Id (PK) title description priority complete

1 Go to store To pick up eggs 4 0

2 Haircut Need to get length 3 0


1mm

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
STARTING DATABASE TABLE (TODOS)

Id (PK) title description priority complete

1 Go to store To pick up eggs 4 0

2 Haircut Need to get length 3 0


1mm

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
STARTING DATABASE TABLE (TODOS)

Id (PK) title description priority complete

1 Go to store To pick up eggs 4 0

2 Haircut Need to get length 3 0


1mm

3 Feed dog Make sure to use 5 0


new food brand

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
STARTING DATABASE TABLE (TODOS)

Id (PK) title description priority complete

1 Go to store To pick up eggs 4 0

2 Haircut Need to get length 3 0


1mm

3 Feed dog Make sure to use 5 0


new food brand

4 Water plant Inside and Outside 4 0


plants

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
STARTING DATABASE TABLE (TODOS)

Id (PK) title description priority complete

1 Go to store To pick up eggs 4 0

2 Haircut Need to get length 3 0


1mm

3 Feed dog Make sure to use 5 0


new food brand

4 Water plant Inside and Outside 4 0


plants

5 Learn something new Learn to program 5 0

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
STARTING DATABASE TABLE (TODOS)

Id (PK) title description priority complete

1 Go to store To pick up eggs 4 0


2 Haircut Need to get length 3 0
1mm

3 Feed dog Make sure to use 5 0


new food brand

4 Water plant Inside and Outside 4 0


plants

5 Learn something new Learn to program 5 0

6 Shower You have not 5 0


showered in days

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
DELETE

Id (PK) title description priority complete owner

3 Feed dog Make sure to use 5 0 2


new food brand
4 Water plant Inside and 4 0 2
Outside plants

6 Shower You have not 5 0 2


showered in days

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
SELECT SQL QUERIES

SELECT * FROM todos;

Select ALL columns and rows

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
SELECT SQL QUERIES

SELECT title FROM todos;

Select just title from columns

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
SELECT SQL QUERIES

SELECT description FROM todos;

Select just description from columns

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
SELECT SQL QUERIES

SELECT title, description FROM


todos;
Select title, description from columns

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
SELECT SQL QUERIES

SELECT title, description, priority FROM


todos;
Select title, description and priority from columns

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES

WHERE Clause

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES

SELECT * FROM todos WHERE priority=5;

Select ALL rows & columns WHERE priority = 5

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES

SELECT * FROM todos WHERE title=‘Feed dog’;

Select ALL rows & columns WHERE title= Feed dog

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES

SELECT * FROM todos WHERE id=2;

Select ALL rows & columns WHERE id= 2

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
UPDATE SQL QUERIES

UPDATE Clause

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES

UPDATE todos SET complete=True WHERE


title=‘Learn something new’;

Update ALL rows & columns to now have complete = True


WHERE id = 5

1 == True
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES

UPDATE todos SET complete=True WHERE id=5;

Update ALL rows & columns to now have complete = True


WHERE id = 5

1 == True
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
DELETE SQL QUERIES

DELETE Clause

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
DELETE SQL QUERIES

DELETE FROM todos WHERE id=5;

Delete ALL rows and columns where id =


5

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
DELETE SQL QUERIES

DELETE FROM todos WHERE complete=0;

Delete ALL rows and columns where complete =


0

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
ONE TO MANY INTRODUCTION

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A ONE TO MANY RELATIONSHIP

A user can have many todos

Todo

Todo
User
Todo

Todo

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A ONE TO MANY RELATIONSHIP

Users & Todos

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A ONE TO MANY RELATIONSHIP

Users & Todos


Id (PK) Id (PK)
email title
username description
first_name
last_name priority
hashed_password complete
is_active Owner (FK)

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A ONE TO MANY RELATIONSHIP
Add new
column

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A ONE TO MANY RELATIONSHIP

Users

Todos

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
FOREIGN KEYS

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A FOREIGN KEY?

A foreign key (FK) is a column within a relational database table


that provides a link between two separate tables.
A foreign key references a primary key of another table
Most relational databases need foreign keys to be able to link
tables together to present data

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
FOREIGN KEYS

SELECT * FROM todos;

Select ALL columns and rows

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
FOREIGN KEYS

SELECT * FROM users;

Select ALL columns and rows

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
Each API request a user will have their ID attached
If we have the user ID attached to each request, we can
use the ID to find their todos

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES

SELECT * FROM todos WHERE owner=1;

Select ALL rows & columns WHERE owner = 1

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES

SELECT * FROM todos WHERE owner=2;

Select ALL rows & columns WHERE owner = 1

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
MYSQL INTRODUCTION

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS MYSQL

Open-source relational database


management system
Requires a server
Production ready
Scalable
Secure

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHO USES/USED MYSQL?

Facebook YouTube Tesla

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
POSTGRESQL INTRODUCTION

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS POSTGRESQL

Production ready
Open-source relational database
management system
Secure
Requires a server
Scalable

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT WILL WE COVER?

How to install PostgreSQL


Windows
Mac
Setup SQL tables
Connect PostgreSQL to our
application

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHO USES/USED POSTGRESQL?

Appl Reddit Twitch


e

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
ROUTING INTRODUCTION

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS ROUTING

Rare that you want your entire


application to be on a single file
Flexible tool to structure your
application
Scalable architecture
Organize file structure

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
NEW PROJECT STRUCTURE
TodoApp

TodoApp/routers TodoApp/
main.py company (new)

auth.py companyapis.py
database.py

todos.py dependencies.py
models.py

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JINJA SCRIPTS

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT JINJA?

Fast, expressive and extensible


templating language
Able to write code similar to Python
in the DOM
The template is passed data to
render within the final document

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT ARE JINJA TEMPLATING TAGS AND SCRIPTS?

Jinja tags allows developers to be confident while working with backend data, using tags that are similar
to HTML.

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT ARE JINJA TEMPLATING TAGS AND SCRIPTS?

Now image we have a list of todos that we retrieved from the database. We can pass the entire list
of todos into the front-end and loop through each todo with this simple ‘for loop’ on the template.

todos.py
Home.html

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT ARE JINJA TEMPLATING TAGS AND SCRIPTS?

We can also use Jinja templating language with if else statements. One thing that may stand out is the double brackets with
todos|length

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
LET’S LEARN GIT

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS GIT?

Free and open-source distributed


version control system
Can handle small to large
applications and projects
Allows team members to use same
files by distributed branches/
environments

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Version 1

class MathFunctions: Simple Python Class

def addition(a, b): Addition Function


return a + b

We need to add subtraction to MathFunctions

LET’S CODE TOGETHER © CODINGWITHROBY


GIT EXAMPLE?
Version 2

class MathFunctions: Simple Python Class

def addition(a, b): Addition Function


return a + b

def subtraction(a, b):


Subtraction Function
return a - b

New Function New Version Of Code

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Version 3

class MathFunctions: Simple Python Class

def addition(a, b): Addition Function


return a + b

def subtraction(a, b):


Subtraction Function
return a - b

def multiplication(a, b): Multiple Function


return a * b
LET’S CODE TOGETHER © © CODINGWITHROBY
GIT EXAMPLE?
Version 1
Version Control

Version 2

Version 3
Commit 1

Commit 2

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS GIT?

Class MathFunctions Bill’s Code Sarah’s Code

addition subtraction

Multiplication Division Square


Root Power

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS GIT?

Class MathFunctions) Bill’s Code Sarah’s Code

Functions

New New
Function Function

LET’S CODE TOGETHER © © CODINGWITHROBY


Git Repo & Version Control
GIT?
todos.py home.html
Commit 1
Code files (for app)

auth.py styles.css

todos.py home.html

Commit 2
todos.py
auth.py styles.css

new.py
Commit 3

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS GIT?

Free and open-


source distributed
version control
system

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS GIT?

Track Changes
Free and open- Version Control
source distributed Allows team members to use same
version control files without needing to sync every time
system

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT BASICS

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Version 1
Version Control

Version 2

Version 3
Commit 1

Commit 2

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Git Command Details
git init Initializes a new, empty repository

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Git Command Details
git init Initializes a new, empty repository

git add . Adds files from a non-staged area to


a staging GIT area

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Git Command Details
git init Initializes a new, empty repository

git add . Adds files from a non-staged area to


a staging GIT area
git commit –m “info here” Move files from a staging area to a
commit

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Git Command Details
git init Initializes a new, empty repository

git add . Adds files from a non-staged area to


a staging GIT area
git commit –m “info here” Move files from a staging area to a
commit
git checkout <commit #> Open up previous commit

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Git Command Details
git init Initializes a new, empty repository

git add . Adds files from a non-staged area to


a staging GIT area
git commit –m “info here” Move files from a staging area to a
commit
git checkout <commit #> Open up previous commit

git log Shows committed Snapshots

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT BASICS
python-git-basics GIT
git init

stashed
un-stashed

git add .

Commit 1 Complete git commit –m “First


commit.”
LET’S CODE TOGETHER © © CODINGWITHROBY
GIT BASICS python-git-basics

stashed

un-stashed

git add .

git commit –m “Added addition


Commit 2 Complete functionality”

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT BASICS
2 Different Commits

commit
aabbccddee112233445566
python-git-basics Author: Eric Roby
git log “Added Addition Function”

commit
aabbccddee112233445567
Author: Eric Roby
git checkout “First Commit”
aabbccddee112233445567
LET’S CODE TOGETHER © © CODINGWITHROBY
GIT BRANCHES

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS A GIT BRANCH?

A pointer - to take a A pointer of data change


snapshot of a
Isolation of feature development
change. Branches
can be merged into Linear development
other branches

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Git Command Details
git branch <branch name> Create new isolated branch

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Git Command Details
git branch <branch name> Create new isolated branch

git checkout branch <branch name> Change root to branch selected

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Git Command Details
git branch <branch name> Create new isolated branch

git checkout branch <branch name> Change root to branch selected

git switch branch <branch name> Same as above new command as of


Git (2.23)

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT BRANCHES?

All code is currently in the master branch

git branch multiplication-branch New branch

Checkout new branch


git checkout multiplication-branch

Multiplication-
master branch
branch

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?

Master Branch Multiplication-branch

addition addition

subtraction
subtraction

multiplication
multiplication

merge

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT BRANCHES python-git-basics
detached-head
merge
multiplication-
branch
git checkout
master branch multiplication-branch

git merge <commit id>

master branch
git commit –m “adding
git merge multiplication-
multiplication function.”
branch
LET’S CODE TOGETHER © © CODINGWITHROBY
WHAT IS GITHUB?

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS GITHUB?

Git Repository hosting service


User friendly interface
Large development platform

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS GITHUB?

Free and open-


Top Git Repository
source distributed
hosting service
version control
available
system

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS GITHUB?
GitHub

Git

All Git data is saved on Cloud. Can


access version control and team’s
merges

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS RENDER?

LET’S CODE TOGETHER © CODINGWITHROBY


WHAT IS RENDER?

Platform as a service (PaaS)


Helps developers build, run and
operate applications entirely on the
cloud
Developers can focus on coding and
not have to worry about the
infrastructure of their applications

LET’S CODE TOGETHER © CODINGWITHROBY


RENDER PRICING?

Pricing depends on many factors of


how you want your application to
perform online
Free Trial
Free Plan
Businesses of all sizes use Render
as their cloud PaaS provider.

LET’S CODE TOGETHER © CODINGWITHROBY


WHAT IS RENDER?

Code deployment system


Continuous Integration & Continuous
Deployment (CI/CD)
Load Balancing
and more…

Focus on Code

LET’S CODE TOGETHER © CODINGWITHROBY


WHAT IS RENDER?

LET’S CODE TOGETHER © CODINGWITHROBY


DIFFERENT PLATFORMS?

LET’S CODE TOGETHER © CODINGWITHROBY


THANK YOU!!

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
CONTACT ME!

codingwithroby@gmail.com
Instagram: @codingwithroby

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
LET'S LEARN PYTHON

Assignment!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

Variables!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

Comments!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

String
Formatting!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

User Input!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

Lists!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

Sets & Tuples!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

Boolean &
Operators!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

If Else!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

Loops!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

Dictionaries!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

Functions!

LET’S CODE TOGETHER © © CODINGWITHROBY

You might also like