Introduction to FastAPI

Pradosh K
DataUniverse
Published in
7 min readJun 2, 2023

What is an API?

Imagine you’re at a restaurant, and you want to order some food. In order to get the food you want, you talk to the waiter and tell them your order. The waiter then takes your order to the kitchen, where the chefs prepare the food according to your request. Finally, the waiter brings your food back to you, and you can enjoy your meal.

In this scenario, the waiter is like an API (Application Programming Interface). An API is a way for different software applications to communicate and exchange information, just like you communicated with the waiter to get your food order to the kitchen.

Instead of people, APIs allow different computer programs, apps, or websites to talk to each other and share data. For example, when you use a mobile app to check the weather, the app uses an API to get the current weather information from a weather service. The app sends a request to the API, asking for the weather data, and the API responds with the requested information.

APIs make it possible for different apps and services to work together and share information seamlessly. They define a set of rules and protocols that specify how one program can request data from another program and how the data will be sent back.

Think of APIs as a language that allows different applications to understand each other and collaborate. They enable developers to build new apps or integrate existing ones by leveraging the functionalities provided by other services.

So, APIs are like messengers that help different software applications talk to each other, exchange data, and work together to provide us with the services and information we need in our digital world.

What is FastAPI?

FastAPI is a Python web framework that helps you build APIs (Application Programming Interfaces) quickly and easily. It provides a set of tools and features that make it simple to create web applications that can receive and send data over the internet.

As explained on top , Think of an API as a way for different applications to talk to each other. For example, when you use a mobile app and it fetches data from the internet, it’s probably using an API to get that information. FastAPI helps you build the part of the application that provides the data and services that other apps can use.

FastAPI is designed to be fast (as the name suggests) and efficient. It uses a modern approach called asynchronous programming, which allows multiple tasks to run at the same time without blocking each other. This means your API can handle many requests from different users without slowing down.

FastAPI also has a user-friendly interface. It’s designed to be easy to understand and work with, even if you’re new to web development. It uses Python, a popular programming language known for its simplicity and readability. With FastAPI, you can write clean and organized code to build your API.

One cool thing about FastAPI is that it automatically generates documentation for your API based on the code you write. This documentation helps other developers understand how to use your API and what data it expects. It’s like having a manual for your API without having to write it yourself.

Overall, FastAPI is a powerful tool that simplifies the process of building APIs. It helps you create web applications that can communicate with other apps, handle multiple requests efficiently, and generate documentation automatically. It’s a great choice if you want to create APIs using Python quickly and easily.

What is asynchronous programming?

Imagine you have a bunch of tasks to do, like homework assignments or chores around the house. Normally, you would do one task at a time, finish it, and then move on to the next task. However, sometimes you come across tasks that take a long time to complete, like waiting for a webpage to load or downloading a large file. It’s like waiting in line for something to happen before you can move on to the next task.

Now, imagine if you could do something else while waiting for those slow tasks to finish. For example, while waiting for a webpage to load, you could start working on another assignment or do something fun like playing a quick game on your phone. This way, you’re not wasting time just waiting for one task to finish before starting another.

FastAPI, being built on top of the Python programming language, leverages Python’s native support for asynchronous programming to handle asynchronous operations.

In FastAPI, you can define asynchronous routes and functions using the async and await keywords. By marking a function or route as async, you indicate that it can perform asynchronous operations. This allows the function or route to pause its execution while waiting for external resources, such as a database query or an API call, without blocking the entire application.

Here’s a more practical example that demonstrates how FastAPI can handle asynchronous operations, specifically fetching data from an external API asynchronously

from fastapi import FastAPI
import httpx

app = FastAPI()

async def fetch_data(url):
async with httpx.AsyncClient() as client:
response = await client.get(url)
return response.json()

@app.get("/data")
async def get_data():
data_url = "https://api.example.com/data"
data = await fetch_data(data_url)
return {"data": data}

In this example, we have a new function called fetch_data that performs an asynchronous HTTP GET request using the httpx library. The fetch_data function is defined as a coroutine using the async keyword.

In the get_data endpoint, we call the fetch_data coroutine using the await keyword to asynchronously fetch data from the external API. The execution of the get_data function will be paused until the response is received from the API.

This allows FastAPI to handle multiple requests concurrently. While one request is waiting for the response from the external API, FastAPI can process other requests, making the application more efficient and responsive.

Set up and execute the most basic route using Fast API

  1. First create directory and navigate inside the directory and then run this command.

python -m venv venv

2. Then activate the environment. These two steps is primarily to do this development in an isolated environment.

C:\<directoryname>\venv\Scripts>activate.bat

3. Then Install FastAPI inside it with the dependecies

pip install fastapi[all]

4. Then Open VS code or Pycharm and save this code in a file and save in the created directory

from fastapi import FastAPI 
app = FastAPI()

@app.get("/")
def root():
return {"message": "Hello World from FastAPI"}

5. Go to command prompt and navigate to the directory and hit this command

uvicorn main:app — reload

This command refers to :

  • main: the file main.py (the Python “module”).
  • app: the object created inside of main.py with the line app = FastAPI().
  • — reload: make the server restart after code changes. Only use for development.
INFO:     Will watch for changes in these directories: ['C:\\personalwork\\apitutorial\\app']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [16600] using WatchFiles
INFO: Started server process [13332]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: 127.0.0.1:64425 - "GET / HTTP/1.1" 200 OK

You can open the browser and paste the URL and you can see the JSON response as:

Boosters Tips

In FastAPI, the automatic conversion of Python dictionaries to JSON is handled by the framework itself. FastAPI uses the JSONResponse class from the fastapi.responses module to handle JSON serialization and response generation.

FastAPI automatically detects the return type of your endpoint functions. When a Python dictionary is returned, FastAPI recognizes it as JSON data and serializes it to a JSON string. This JSON string is then included in the HTTP response body with the appropriate content type header (application/json) to indicate that the response contains JSON data.

By automatically converting Python dictionaries to JSON, FastAPI simplifies the process of returning structured data from your API endpoints. It allows you to work with Python objects and dictionaries internally within your application, while seamlessly transforming them into a format that can be easily transmitted and understood by clients.

Interactive API Docs

You can also see the automatic interactive API documentation (provided by Swagger UI): http://127.0.0.1:8000/docs

I hope you enjoyed reading this article. I have tried to explain the basic concept. In the later session, we will go more in-depth.

Thank you. Please subscribe and like. That would give me more energy to write interesting article in future.

--

--