FastAPI Framework : How To Create Your First API Using FastAPI

Feb 5 2023 . 3 min read

Fastapi is an another most popular framework of python for building powerful web api's just like Django. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. python for building powerful web api's just like Django. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints.

Installation

Before move to create our first api, let's install these two required dependencies.

pip install fastapi
pip install "uvicorn[standard]"

Let's create an API

Now create a main.py file and open it in any code editor.

main.py
  1. from fastapi import FastAPI
  2. app = FastAPI()
  3. @app.get("/")
  4. def read_root():
  5.     return {"Hello": "World"}

Run the Server

To start the development server just hit this command in your terminal.

uvicorn main:app --reload

It will start the development server on the default port 8000

INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

If you want to change the port you can add --port <portnumber>

uvicorn main:app --reload --port 5000

Check the output

Open your browser at http://localhost:8000
{"Hello" : "World" }

Interactive API docs by Swagger UI

If you want to see the automatic interactive API documentation provide by (Swagger UI)

http://localhost:8000/docs

Alternative API docs by ReDocs

If you want to see the automatic interactive API documentation provide by (ReDoc)

http://localhost:8000/redocs

Conclusion

That's it, We have created our first basic and simple api using fastAPI. You can create more powerful api using FastAPI, check it out the fastAPI docs