Python: Setting up Fast API

Athar Naveed
7 min readMay 16, 2024

--

Assalam o Alaikum and Hello there! In this article, we are going to set up Fast API for use with Python.

Let’s start with a little intro to FAST API🚀!

English
(Article Roman Urdu mein parhnay ky lye, article ko akhir tk scroll krein)

As the name says, Fast API is Fast, it increases the speed of API development by 200–300%.

Development speed increased by 200–300%

Because it is built over Starlette (A lightweight framework/toolkit) and Pydantic (A most used Python library for data validation).

This article will start the series of performing a simple CRUD using:

  1. FAST API (API’s)
  2. Python (Backend lang.)
  3. Streamlit (Frontend Python Framework)
  4. Postgres of Neondb (As a database)
  5. Uvicorn (As a server, that’ll detect our file changes)

I’ll try to make it as light as possible and beginner-friendly.

So, let’s start

Installing Fast API

  1. Creating venv:

There are 2 ways to create a venv:
1. Using simple Python command.
2. Using uv (a new Python Package manager).

# 1. Using simple python command
python -m venv path_to_venv/venv_name

# 2. using uv
uv venv

If you don’t have uv installed you can read my blog here.

2. Activating venv:

# activating venv in simple python
venv\Scripts\activate.bat

# activating in uv
'''Windows'''
.venv\Scripts\activate

'''Linux'''
source .venv/bin/activate

3. Installing Fast API and Uvicorn:

# using pip
pip install fastapi uvicorn

# using uv
uv pip install fastapi uvicorn

Creating a File

Inside the working directory, I’ll be creating a file named ‘server.py’, you can name it anything you want.

Setting up Fast API

Now add this code into your file.

from fastapi import FastAPI

app: FastAPI = FastAPI()

# simple get request
@app.get("/")
def index():
return {"message": "Hello Fast API", "status": 200}

if __name__ == "__main__":
import uvicorn
uvicron.run("server:app",reload=True)

Let me explain, what the above code is doing.

  1. We are importing FastAPI from fastapi, that’s simple.
  2. We have created an object of FastAPI named app and provided the type of FastAPI.
  3. Next, we have a simple get request, starting with:
  4. ‘@app.get(“/”)’: It is a decorator, that is making a GET request, whenever this “/” path will be hit on the server.
  5. It is a default path, you can provide anything here.
  6. ‘index()’: It is a method associated with the decorator, that whenever this “/” path will hit with a get request, run this method.
  7. This method returns a JSON response, containing the message and status.
  8. “ __name__ == ‘__main__’ ”: These are dunder (double underscore) attributes that do something magical💥, I’ll write a whole article over them. But for now, let’s say it is a condition that’ll be always True.
  9. ‘uvicorn’: We have simply imported uvicorn here, you can do it outside as well.
  10. ‘uvicorn.run’: This method will start the uvicorn server, and takes some arguments:
  11. ‘server:app’: where server is the name of the file, and app is the name of the object.
  12. ‘reload=True’: By default, the server doesn’t refresh/restart itself, if we make any changes in the files associated with it so, we have to pass this argument and set it to True.
    You can also specify,
    port’: By default is 8000.
    host’: By default is 127.0.0.1
    there are many more.

And that’s it, time⌚ to start our server.

There are many ways to start a uvicorn server for FastAPI.
Also, note you can even start a server without using uvicorn.

Starting our server

Go to the terminal and run your python file,

- windows
py server.py or the name of your file

- linux
python3.10 server.py or the name of your file

Head to your browser and enter the port number in the url, by default it is:

127.0.0.1:8000
JSON Response

Yeah! We have successfully created an API😃.

Swagger UI

You can also perform API requests using Swagger UI (It is a UI tool like Postman, to make API requests), how?

You just have to type, ‘/docs’ with your port number, and it’ll open like this,

http://127.0.0.1:8000/docs

and it’ll show you this screen:

Swagger UI

Click the, “Try it out option”, and then “Execute”.

It’ll return the response either 200 or 400 depending on the type of the response.

Response from API request

That’s it!

See you next time with some exciting work on Python or TypeScript.

Roman Urdu

Assalam o Alaikum! Aaj ky article mein hum Fast API pr kaam krein gy, in Python.

Article shuru krny sy pehly, mein apko FAST API 🚀 ka thora sa intro dy deta hun.

Jesa ky humein isky name sy pta chal rha hai ky Fast API bohat Fast hai, kyunky ye API development ki speed ko 200–300% barha deta hai.

Development speed increased by 200–300%

Kyunky ye Starlette (Ye aik lightweight framework/toolkit hai) aur Pydantic (Aik most used library hai Python ki data validation ky lye) pr bni hui hai.

Is article ky sath hi hum aik simple CRUD perform krein gy, in technologies ko istemal krty huye:

  1. FAST API (API’s)
  2. Python (Backend lang.)
  3. Streamlit (Frontend Python Framework)
  4. Postgres of Neondb (database ky lye)
  5. Uvicorn (server ky tor pr, joky humaray project mein file changes ko detect kry ga).

Mein koshih krun ga ky, is article ko aisy likhun ky apko ba-asani samajh ajaye.

Tou shuru krty hain!

Installing Fast API

  1. Sb sy pehly hum venv, bnayein gy:

Venv bnany ky 2 tareeky hain:
1. Simple Python command ko use krky.
2. uv ko use krky (uv aik new Python Package Mangaer hai).

# Using simple python command
python -m venv path_to_venv/venv_name

# using uv
uv venv

Agar aap ky pass uv installed nhi hai tou, aap mera ye blog parh skty hain.

2. Phir venv ko activate krein:

# activating venv in simple python
venv\Scripts\activate.bat

# activating venv in uv
'''Windows'''
.venv\Scripts\activate

'''Linux'''
source .venv/bin/activate

3. Fast API aur Uvicorn ko install krein:

# using pip
pip install fastapi uvicorn

# using uv
uv pip install fastapi uvicorn

Creating a File

Apnay project ky folder ky ander aik file create krein, mein yahan pr file ka name “server.py” rkh rha hun. Aap iska name kuch bhi rkh skty hain.

Setting up Fast API

Ab apni file mein ye code likhein:

from fastapi import FastAPI

app: FastAPI = FastAPI()

# simple get request
@app.get("/")
def index():
return {"message": "Hello Fast API", "status": 200}

if __name__ == "__main__":
import uvicorn
uvicron.run("server:app",reload=True)

Mein explain krta hun ky, ye code kya kr rha hai.

  1. Hum fastapi sy FastAPI ko import kr rhy hain.
  2. Isky baad humny FastAPI ka aik object bnaya hai, jiska name app rkha hai, aur usko data type FastAPI di hai.
  3. Usky baad humaray pass aik simple GET request hai, jo ky shuru hoti hai:
  4. ‘@app.get(“/”)’: Ye aik Python ka decorator hai, joky GET request kr rha hai, jb bhi ye, “/” path server pr hit hoga.
    Ye aik default path hai, aap iski jagah pr kuch aur bhi dy skty hain.
  5. ‘index()’: Ye aik method/func. hai joky decorator ky sath associated hai. Jb bhi server pr ye “/” path hit hoga tou index ka method call hoga GET request wala.
  6. Ye method apko JSON format mein response return krta hai, jismein aik message aur aik status hai.
  7. ‘ __name__ == “__main__” ‘: Ye dunder (double underscore) attributes hain joky kuch jadui kaam krty hain💥. Mein is pr aik aleihda article likhun ga. Likin, filhal ye smjh lein ky, ye aik aisi condition hai joky humesha True rhy gi.
  8. ‘uvicorn’: Humny simply uvicorn ko import kya hai, aap isko top pr bhi kr skty hain.
  9. ‘uvicorn.run’: Ye uvicorn ky server ko start krta hai, aur kuch arguments accept krta hai:
    ‘server:app’: Jahan server file ka name hai, jbky app us object ka name hai, jo humny FastAPI ka bnaya hai.
    ‘reload=True’: By default, server khud ba khud restart/refresh nhi hota, agar hum apnay project ki kisi bhi file mein change krein tou, humein server ko dobara start krna prta hai, is sy bachnay ky lye, humny yahan reload ko True set kya hai.
    Aap yahan pr kuch aur arguments bhi pass kr skty hain,
    ‘port’: By default, ye 8000 hoti hai.
    ‘host’: By default ye 127.0.0.1 hoti hai.
    aur bohat sari hain.

Aur bs, ab waqt ⌚ hai, apnay server ko start krny ka.

Uvicorn ky server ko start krny ky aur bohat sy tareeky hain.
Aik aur cheez, aap sirf FastAPI sy bhi server start kr skty hain.

Starting our server

Terminal pr ja kr apni Python file ko run krein,

- windows
py server.py or the name of your file

- linux
python3.10 server.py or the name of your file

Ab apnay browser pr ja kr port number enter krein, joky by default hai:

127.0.0.1:8000
JSON Response

Mubarak Ho! Humny apna pehla API create kr lya hai.😀

Swagger UI

Aap apni API requests Swagger UI (Ye aik UI tool hai, bilkul Postman ki tarah ka) ko use krty huye bhi kr skty hain, kesy?

Apko sirf port number ky agay, ‘/docs’ add krna hai, aur ye open ho jayega,

http://127.0.0.1:8000/docs

aur apko kuch is tarah ki screen show hogi:

Swagger UI

“Try it out option” pr click krny ky baad, “Execute”.

Ye apko 200 ya 400 ka response return kry ga, depend krta hai ky response mein kya arha hai.

Response from API request

That’s it!

Aglay blog mein miltay hain, Python aur TypeScript mein kuch zabardast krty hain.

--

--

Athar Naveed
Athar Naveed

Written by Athar Naveed

Carving a path for junior devs so that they can easily navigate through the hurdles that made my learning experience challenging. Also loves Gardening!

No responses yet