Build simple API to create a new user into the database with FastAPI

Image for post
Image for post
Photo by Jamie Street on Unsplash

Previously, I’ve written a blog for how to build API service with spring-boot and spring.

In today part, I will cover what FastAPI is, SQLAlchemy for working with MySQL, and simple API to create a new user account.

I.What is FastAPI

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.

The key features are:

  • Fast: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python frameworks available.
  • Fast to code: Increase the speed to develop features by about 200% to 300% *.
  • Fewer bugs: Reduce about 40% of human (developer) induced errors. *
  • Intuitive: Great editor support. Completion everywhere. Less time debugging.
  • Easy: Designed to be easy to use and learn. Less time reading docs.
  • Short: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
  • Robust: Get production-ready code. With automatic interactive documentation.
  • Standards-based: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.

You can checkout more information from their official document page

II.Get started with “Hello {name}” with FastAPI:

  1. Install FastApi:

To install FastAPI, simply use pip install fastapi

You will also need uvicorn to run the server, so install uvicorn also

Above is how you install libraries in Python globally. But I would suggest you would install in your virtual environment.

For me I usually work with pipenv

So below is how to install library with pipenv

2. Implement API which return “Hello {name}”

First, just create the new Python project in your favorite IDE, then create a main.py file like below

To run this, simply :

The result will be like this when you open the url in your browser

Image for post
Image for post

III. Build simple API to create new user account into your MySQL db

For doing this, first you need a way to connect to MySQL in Python.

We will be using SQLAlchemy with mysql-connector-python library.

1.SQLAlchemy:

SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.

It provides a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language.

You can find out more information for SQLAlchemy from here

To install SQLAlchemy:

2. Mysql-connector-python

MySQL-connector-python is a self-contained Python driver for communicating with MySQL servers, and how to use it to develop database applications.

You can find out more from the official page.

To install mysql-connector-python:

3.Create a new database with table “user_info” in MySQL:

Create a database name “restapi”

Create a new table name “user_info”CREATE TABLE user_info(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
password VARCHAR(500) NOT NULL,
fullname VARCHAR(50) NOT NULL
);

4.Create a new project for building the service with MySQL in Python

The new project will consists the following files:

  • crud.py : to define method (read,write) to MySQL
  • database.py : for connecting MySQL
  • main.py: main file for build FastAPI service
  • models.py: define class object models for FastAPI
  • schemas.py: define schemas for working with the specific API request/response

database.py:

the database name will be : restapi

the username for database : root

the password for database : cuong1990

models.py

Define the class/object model for userinfo to interact with table “user_info”

schemas.py

Define the base schema and usercreate, userinfo schema for working with API request and response

crud.py

Define the method for create new user and get user by username

main.py

Define for how to build api create_user and raise exception if create new username with username already.

To run the service with fastapi, you can easily run main file by clicking on green button

Image for post
Image for post

Then you can see the service running:

Image for post
Image for post

5.Interact with api using postman:

Create with username already existed:

Image for post
Image for post

Create new user account successfully

Image for post
Image for post

You can checkout sourcecode for this from github.

Happy coding ~~~

Written by

A passionate automation engineer who strongly believes in “A man can do anything he wants if he puts in the work”.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store