A sample Python API written on FastAPI with helping modules for compiling into a single binary using Cython-ization and Python/C API.
Based on perfomance testing, Cython can speed up your project by 3.35 times.
You can check my article about cythonized FastAPI projects with benchmarks (on Russian) on my blog - difhel.dev/blog/cython-fastapi-benchmark. This article also contains some comprehensive instructions how to build and run this code.
main.pyx
- main file, code written on Python (without Cython-flavored feautures), the entry point of the project.routes
- the routes of API (in this example only one router -ftl
with method/method/ftl.test
)builder.c
- C code for compiling filemain.c
.main.c
is auto-generated C-code generated by Cython. This file is a build artifact produced by cythonizingmain.pyx
, the source code.Makefile
- makefile for the project. Options:- cythonize - runs
cython main.pyx
, cythonizing source code. - build - translates the project to
main.c
and compiles it tomain.<arch>.so
shared library file - gcc - compiles the file
main.c
toapp.o
- run - start the project with environment variable
PYTHONPATH=pwd
(needed for Python API) - clean - delete build artifacts
- cythonize - runs
- You are using OS Linux with the bash shell.
- To be honest, this project does not contain any platform-specific things, so you can run it on Windows either, but you should install a C compiler. In case you are using Windows, you can try MinGW compiler. You will also need GNU make for Windows (of course, unless you want to copy and paste all the commands from the Makefile directly).
- Of course, you should have FastAPI installed (
pip3 install fastapi
) - You should have an ASGI server. In this project cythonized version of uvicorn is used. (
pip3 install "uvicorn[standart]"
) - Make sure you have Cython installed (
pip3 install cython
)
- You can use any C compiler that can build Python/C API code, but I recommend you to use standart
gcc
compiler. (sudo apt-get install gcc
)
make && make run
$ curl -i http://localhost:5000/method/ftl.test
HTTP/1.1 200 OK
date: Sat, 16 Sep 2023 08:58:08 GMT
server: uvicorn
content-length: 16
content-type: application/json
{"ping":"pong2"}