Morgan-Phoenix
Posted on June 29, 2021
So In The Previous Part We Made Our First Ever API In This Part I Will Explain What Was The Code Actually Doing. If You Don't Know What I Am Talking About Check The First Part Of This Series Here
The Explaination
This Is The Code I Shared
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
def home():
return {'data':'Get This And Be Happy'}
Now In The First Line We Imported FastAPI
from fastapi
from fastapi import FastAPI
What Is FastAPI?
FastAPI
Is The Main Class You Will Use To Start With The API
Now We Made A Object Called app
Of The Class FastAPI
So We Can Use All The Functions And Methods Provided By This Class.
Then We Did Something Like This @app.get('/)
, If You Don't Know What The @
Symbol Is, Let Me Tell You (If You Know What Is it Please Skip To "Explaining An Endpoint")
These Things Are Called Decorators
In Python(A Decorator allows a user to add new functionality to an existing object without modifying its structure.)
So What Do I Mean Here Is, Lets Say I Created A Function foo
def foo(f):
print('doing')
f()
print('done')
And Then I Created A Function func
And Then Run This
@foo
def func():
print('inside foo')
Here The Function func
Will Be Give To Function foo
As A Parameter, So By Now You Know What Will Be The Result,
doing
inside foo
done
You Will Get This As The Result
Now Enough About Decorators, Lets See What An Endpoint Is
Explaining An Endpoint
Now An Endpoint Is A /some_address
(slash some address) Where Clients Can Come And Do Stuff Like We Have google.com/home
, Here We Defined Our Endpoint As /
. This Means Who Ever Comes To http://127.0.0.1:8000
(or whatever domain name our api is running), That Client Is Recived Where We Defined /
.
Now We Wrote A Function Just Below It, This Function Runs Everytime A Clients Visits /
and may return something, Similarly If We Create /hello
, The Function Defined Below Will Be Executed If Someone Visits /hello
.
In The Function We Did Not Do Something Crazy, All We Did Is Returned A Dictonary. But.... Why A Dictonary?
Why A Dictonary?
Now If You Noticed We Used A Dictonary, This Raises a Question, Why? Why A Dictonary? We Use A Dictonary Because We Can't Use Strings To Send Data Over HTTP, We Use Something Called JSON. JSON Is a Format Of Data That Is Commomly Used To Talk Over HTTP. A JSON Data Looks Something Like This {'data':'I AM JSON'}
. Get The Point Now? FastAPI Converts A Dict
object to a JSON
Object.(See here or here to read more about JSON)
And That's All We Did.
In The Next Post I Will Tell How To Accept Something As A Parameter And Will Explain It In The Same Post
See You All In The Next Post, Till Then Keep Practicing.
Posted on June 29, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.