A Simple πŸ€“ yet Powerful πŸš€ Server with Python 🐍

Rajesh Joshi - Jan 4 '22 - - Dev Community

Python is very well known for it's simplicity 🀩. Which is a plus point if you are just getting started in the programming world.

In this post, you'll be learning how to create a simple FastAPI πŸš€ server in Python 🐍.

FastAPI is really handy to get started with backend development in python. In this post, you'll see a simple code demo of FastAPI.

So let's get started πŸš€


Setup Python Environment

Open a directory, open terminal or cmd and write the following command to create a virtual environment with Python v3

$ python3 -v venv env
Enter fullscreen mode Exit fullscreen mode

Activate the Virtual Environment

Windows

$ .\env\Scripts\activate
Enter fullscreen mode Exit fullscreen mode

Linux or Mac

$ . env/bin/activate
Enter fullscreen mode Exit fullscreen mode

Install the Dependencies

Install FastAPI and other dependencies

(env) $ pip install fastapi "uvicorn[standard]"
Enter fullscreen mode Exit fullscreen mode

Code πŸš€

Create main.py file

Import FastAPI

from fastapi import FastAPI
Enter fullscreen mode Exit fullscreen mode

Create FastAPI instance, app

app = FastAPI()
Enter fullscreen mode Exit fullscreen mode

Write a route, on which you will be hitting the server (Requesting for some Resource).

@app.get("/")
Enter fullscreen mode Exit fullscreen mode

This is a root route (eg. http://127.0.0.1:8000/)

Now, Write a function, which will be trigerred when you hit this API end-point

def index():
    return {"msg": "Hello, World!"}
Enter fullscreen mode Exit fullscreen mode

Full Code πŸ€“

Combining the above script will result the main.py a this-

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def index():
    return {"msg": "Hello, World!"}
Enter fullscreen mode Exit fullscreen mode

Spin up the FastAPI Server πŸš€

(env) $ uvicorn main:app --reload

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [28720]
INFO:     Started server process [28722]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
Enter fullscreen mode Exit fullscreen mode

Now, open http://127.0.0.1:8000/ in your browser, you'll se your first server serving the clients.

Hello, World!


Explore FastAPI πŸš€

Now, you have your first server running. You can walk through the FastAPI Docs. and explore the possibilities.


Hurray! You just learned how to setted up A Simple πŸ€“ yet Powerful πŸš€ Server with Python 🐍.


I hope, you guys liked this quick tutorial. If so, then please don't forget to drop a Like ❀️

And also, help me reach 1k Subscribers 🀩, on my YouTube channel.

Happy Coding! πŸ˜ƒπŸ’»

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .