Python

Getting Started with Python FastAPI

Hello in this tutorial, we will understand how to use FastAPI in python programming to develop fast and high-performance Restful endpoints.

1. Introduction

FastAPI is a fast and high-performance web framework for building api with python 3.6+. It offers many features like:

  • High performance
  • Automatic interactive code generation
  • Offers great editor support and documentation

In this tutorial, we will focus on the basic implementation of FastAPI and play around with it.

1.1 Setting up Python

If someone needs to go through the Python installation on Windows, please watch this link. You can download the Python from this link.

2. Variables in Python

I am using JetBrains PyCharm as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Creating a requirements file

Add the below code to the requirements file. The file will be responsible to download and install the packages required for this tutorial.

requirements.txt

1
2
fastapi
uvicorn

2.2 Creating an implementation file

Add the below code to the python script. The script will be responsible to expose the Restful endpoints using the FastAPI and will also generate the interactive swagger documentation automatically.

  • Health check endpoint
  • Get all todos endpoint
  • Get todo by id endpoint

You’re free to play around with these methods as per your wish.

index.py

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# fast api implementation.
 
import uvicorn
from fastapi import FastAPI, APIRouter
 
TODOS = [
    {
        "id": 1,
        "text": "Learn about Polymer",
        "created_at": "Mon Apr 26 06:01:55 +0000 2015",
        "Tags": [
            "Web Development",
            "Web Components"
        ],
        "is_complete": "true"
    },
    {
        "id": 2,
        "text": "Watch Pluralsight course on Docker",
        "created_at": "Tue Mar 02 07:01:55 +0000 2015",
        "Tags": [
            "Devops",
            "Docker"
        ],
        "is_complete": "true"
    },
    {
        "id": 3,
        "text": "Complete presentation prep for Aurelia presentation",
        "created_at": "Wed Mar 05 10:01:55 +0000 2015",
        "Tags": [
            "Presentation",
            "Aureia"
        ],
        "is_complete": "false"
    },
    {
        "id": 4,
        "text": "Instrument creation of development environment with Puppet",
        "created_at": "Fri June 30 13:00:00 +0000 2015",
        "Tags": [
            "Devops",
            "Puppet"
        ],
        "is_complete": "false"
    },
    {
        "id": 5,
        "text": "Transition code base to ES6",
        "created_at": "Mon Aug 01 10:00:00 +0000 2015",
        "Tags": [
            "ES6",
            "Web Development"
        ],
        "is_complete": "false"
    }
]
 
# 1
app = FastAPI(
    title="Hello world app"
)
 
# 2
api_router = APIRouter()
 
 
# 3
 
@api_router.get("/", description="health check", status_code=200)
def index():
    return {
        "status": "ok",
        "message": "app is up and running"
    }
 
 
@api_router.get("/todos", description="get all todo items", status_code=200)
def get_todos():
    print("Getting all todo list")
    return {
        "status": "ok",
        "items": TODOS
    }
 
 
@api_router.get("/todo/{key}", description="get todo item by id", status_code=200)
def get_todo(key: int):
    print("Getting todo id={}".format(key))
    result = [todo for todo in TODOS if todo["id"] == key]
    if result:
        return {
            "status": "ok",
            "item": result[0]
        }
    else:
        return {
            "status": "not_found",
            "message": "resource not found"
        }
 
 
# 4
app.include_router(api_router)
 
# driver code
if __name__ == '__main__':
    uvicorn.run(app, host="localhost", port=5001, log_level="debug")

Run this python script once the module dependency is completed and if everything goes well the application will be started on the port number – 5001 as shown in the below logs.

Application logs

1
2
3
4
INFO:     Started server process [24428]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://localhost:5001 (Press CTRL+C to quit)

3. Demo

Open up the browser of your choice and hit the swagger documentation endpoint generated via the FastAPI. The documentation will list the endpoints created above.

Documentation endpoint

If everything goes well the documentation page will be shown as in Fig. 1.

python fastapi - swagger doc
Fig. 1: Swagger documentation

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

4. Summary

In this tutorial, we learned about the FastAPI in python programming to generate the high-performance Restful endpoints. You can download the source code of this tutorial from the Downloads section.

5. Download the Project

This was a tutorial on how to implement FastAPI in python programming.

Download
You can download the full source code of this example here: Getting Started with Python FastAPI
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button