The world’s leading publication for data science, AI, and ML professionals.

Implementing FastAPI in 10 Minutes

Develop, test, and use your custom API

Photo by Levi Elizaga on Unsplash
Photo by Levi Elizaga on Unsplash

API (Application Programming Interface) is a connection between computer programs. In layman’s terms, we can think of API as a Python function where users can perform a task or get certain results when they "call an API". A popular example would be likening API to a waiter, whereby you tell the waiter your order from a menu of choices, and the waiter will communicate that to the kitchen (a "system") that prepares your order and the waiter will return your completed order to you.

APIs are valuable and can be monetized – and almost everything is an API now! If you want to know the weather forecast, the website interface calls a Weather API. If you want to know the shortest route from one location to another, the Google Maps website/mobile application calls the Google Directions Service API. You get the idea.

APIs can be implemented in Python using multiple frameworks, some of which include Django, Flask, or Fastapi. This article is a step-by-step guide on how to develop, test, and use your custom API using the FastAPI framework. You can skip the first two sections if you already have some knowledge of APIs.

Update: This article is part of a series. Check out other "in 10 Minutes" topics here!

Table of Contents

  1. HTTP Methods and Status Codes
  2. Why FastAPI?
  3. FastAPI Setup
  4. Writing API with FastAPI
  5. Testing API
  6. Using API

HTTP Methods and Status Codes

It is important to know what kind of tasks can an API perform, and choose the correct HTTP method for the correct task. Bringing back the waiter example, HTTP methods would liken the items on the menu, whereby "Starters", "Main Course" and "Desserts" are part of the menu, but something like "Bedsheet" does not belong on the menu and cannot be ordered.

There are 5 popular HTTP methods, namely GET, POST, PUT, PATCH, and DELETE which can be used to manage the state of resources.

  • GET: Retrieve an existing resource (read-only)
  • POST: Create a new resource
  • PUT: Update an existing resource
  • PATCH: Partially update an existing resource
  • DELETE: Delete a resource

After processing a request with the HTTP method, there will be an HTTP status code included in the response. In general, the meaning of status code is as such,

  • 2xx: Successful operation
  • 3xx: Redirection
  • 4xx: Client error
  • 5xx: Server error

The full list of status codes can be found here. It is important to look at the status code to ensure that the operation is performed successfully, or debug if there are errors, and return appropriate results back to the user.

Why FastAPI?

FastAPI was launched in 2019, later than popular frameworks such as Django (2006) and Flask (2011), and gained popularity as it is fast and high-performant. Compared to the Flask framework, FastAPI has the following benefits,

  • Asyncio for concurrency: Called with async and await keywords
  • Pydantic for data validation: Enforces schema and detects data type at runtime
  • Swagger UI for automated documentation generation: Enable testing of API endpoints with extension /docs. Documentation also promotes understandability. An alternative to Swagger UI is Redoc, which can be accessed with extension /redoc.
  • Security and authentication features

FastAPI Setup

FastAPI is easy to set up, simply run the following command on Terminal.

$ pip install fastapi
$ pip install uvicorn[standard]

Without further ado, let’s dive into writing some APIs!

Writing API with FastAPI

Implementing APIs follow the same overall structure,

  1. Define an API object, such as app = FastAPI()
  2. Define data type, using Pydantic
  3. Map HTTP method and path to the relevant Python function. The different HTTP methods mentioned in the earlier section can be called with @app.get(), @app.post(), @app.put(), etc. respectively, coupled with the path which can be inserted as @app.get("/path")
  4. Start the API application, run uvicorn main:app --reload on the command line, where main refers to the Python filename and app refers to the API object created in Step 1

Below is a code snippet of a FastAPI implementation demonstration,

The following sections will make reference to the code snippet above, make sure you understand this code snippet!

Testing API

After starting the API application successfully, the console logs will print the URL where API is hosted. It is usually hosted on http://127.0.0.1:8000. The main page follows what is defined in the main "/" path (Line 14–16).

Fig 1: Main page of API - Image by author
Fig 1: Main page of API – Image by author

We can test for various endpoints with the path defined. In this case, I’m testing the /path extension (Line 19–21). Note that entering the path extension performs a GET request.

Fig 2: Extension /path of API - Image by author
Fig 2: Extension /path of API – Image by author

Similarly, I have created a /path/{path_id} extension (Line 29–31) where path_id is an int value. If I input a non-integer value, an error message will return stating that I have an invalid type.

Fig 3: Type checking of API endpoints - Image by author
Fig 3: Type checking of API endpoints – Image by author

The above examples are all performing a GET request, to perform a POST request, we can use the Swagger UI by going to the /docs path extension and testing a sample POST request.

Fig 4: Main page of Swagger UI - Image by author
Fig 4: Main page of Swagger UI – Image by author

Alternatively, we can use a curl command to perform a POST request. The Swagger UI provides the exact curl command to run,

Fig 5: Testing POST requests on Swagger UI— Image by author
Fig 5: Testing POST requests on Swagger UI— Image by author

Congratulations, you have now developed and tested your own custom API! We’ll now see how it can be implemented within your Python scripts as end-users of your API might not be always making curl commands or using the Swagger UI.

Using API

To access and use your API within Python scripts, use the requests library, i.e., requests.get() or requests.post() for GET and POST methods respectively. Input parameters include url denoting API endpoint and json denoting input dictionary.

Results are stored in res object and contain the output in res.json() and HTTP status code in res.status_code.

Fig 6: Using API within Python scripts - Image by author
Fig 6: Using API within Python scripts – Image by author

Hope this article has introduced what are APIs and how to develop, test, and use them with the FastAPI framework. Moving forward, it is useful to explore how to connect your API with a backend database, or even host your API online so it can be made available to more users (not just available on your local laptop!).

Thank you for reading! If you liked this article, feel free to share it.


Related Links

fastapi Documentation: https://fastapi.tiangolo.com/

fastapi Official GitHub: https://github.com/tiangolo/fastapi


Related Articles