Build API with FastAPI and Deploy on AWS
API stands for Application Programming Interface, which allows users to access information and/or functionality from an application. To some people, API is an intimidating jargon, but it shouldn’t be feared. It is a tool which is able to help your application come to life. With the popularity of Python, a lot of frameworks are coming out for developers, such as Django, Flask and FastAPI. In this post, we will focus on FastAPI, which is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. You will learn how to build an API using FastAPI and deploy it to AWS.
FastAPI Installation in Virtual Environment
Locate to the project folder, run ‘python3 -m venv project-name’ in terminal. After this command was done, you will find a folder within your project folder, like this:
To activate this virtual environment, run ‘source fastapi-env/bin/activate’ in terminal (for macOS) OR ‘fastapi-env\Scripts\activate.bat ’(for Windows)
After virtual environment was activated, run ‘pip3 install fastapi’ and ‘pip3 install uvicorn’ .
Create an API
Create a file main.py with:
To check the API, run ‘uvicorn main:app — reload’ in virtual environment, then open your browser at http://127.0.0.1:8000 and http://127.0.0.1:8000/info, you will see the response as:
Till now, you have already created an API that:
§ Receives HTTP requests in the paths ‘/’, ‘/info’ , ‘/info/{name}’ and ‘/info/{id}/score’.
§ All paths take get operations.
§ The path ‘/info/{name}’ and ‘/info/{id}/score’ have path parameters ‘name’ and ‘id’ which take value from route, ‘id’ should be an int.
Interact with FastAPI
For other API frameworks, like Flask, you need to install a postman or something else to interact with your API. However, there is an automatic interactive API doc provided by Swagger UI in FastAPI, so youare able to go to http://127.0.0.1:8000/docs to interact API as follows:
Query Parameters
When we declare other function parameters that are not part of the path parameters, they are parsed as ‘query’ parameters. In the following case, ‘limit’ and ‘score’ are query parameters. The default value of limit is 1, the default value of score is 90, and it should be an integer.
So when we are going to the URL, we need to put the query parameter like: http://127.0.0.1:8000/info?limit=10&score=100.
Request Body
In FastAPI, when we need to send data from browser to API, we need to send it as a request body. A response body is the data API sends to the browser. In FastAPI, we use Pydantic models to declare a request body.
First, we need to import BaseModel from pydantic.
Second, declare data model as a class that inherits from BaseModel.
Third, add it to path operation, declare it the same way as path declaration and query parameters.
Lastly, check the schema of the model in swagger UI.
Create a PostgreSQL Database on AWS
To create a PostgreSQL DB instance on AWS, the first step is to sign in to the AWS management console and open the RDS console.
Click the ‘Create Database’ button, then pick a ‘creation method’ and ‘engine type’.
After all settings are done, choose ‘Create database’.
Connect to PostgreSQL
FastAPI doesn’t require a relational database, but users are allowed to use any relational database, like PostgreSQL, MySQL, SQLite, Oracle, Microsoft SQL Server etc.
To connect with PostgreSQL, we need to use sqlalchemy, which is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. In virtual environment, we need to install sqlalchemy first, then do the following:
SQLALCHEMY_DATABASE_URL can be saved as an environment variable. The format should like: postgresql://user:password@host/postgres.
After the connection is set, we are able to either create tables in postgresql database, or fetch data from it using sqlalchemy. To fetch data, we generally use read_sql method from Pandas. To use ‘read_sql’, we need to at least pass two parameters, one is the query, the other is the connection. Here is an example:
Deploy FastAPI Application to Elastic Beanstalk
To deploy the FastAPI application, first step is to initialize EB CLI repository with the eb init command, like ‘eb init — platform python-3.7 — region us-east-1 CHOOSE-YOUR-NAME’. This command creates a new application and configures your local repository to create environments with the latest Python 3.7 platform version. AWS will look for either a ‘requirements.txt’ or ‘Pipfile.lock’ or ‘Pipfile’ to install dependencies in that order. You should have both a ‘Pipfile.lock’ and ‘Pipfile’ in your repo.
Create an environment and deploy application to it with eb create, like ‘eb create — region us-east-1 CHOOSE-YOUR-NAME’.
When the environment creation process completes, open web site with ‘eb open’. This will open a browser window using the domain name created for your application. You should see the same FastAPI website that you created and tested locally.
Takeaways
Building an API is much easier than you think. FastAPI has so many build-in options that make a lot of sense for building data science APIs. You may also be amazed how easy AWS makes it to deploy and manage web applications. Hope my post can help you get started.