python-multipart
module is required to create a REST API that handles form parameters. The installed
uvicorn
,
however, is an ASGI-based server that will run your FastAPI applications. The
Asynchronous Server
Gateway Interface
(
ASGI
) server that FastAPI uses makes it the fastest Python framework at the time
of writing. The
uvicorn
server has the capability to run both synchronous and asynchronous services.
After the installation and configuration of the essential tools, modules, and IDE, let us now start our
first API implementation using the framework.
FastAPI'>Initializing and configuring FastAPI
Learning how to create applications using FastAPI is easy and straightforward. A simple application can
be created just by creating a
main.py
file inside your
/ch01
project folder. In our online academic
discussion forum, for instance, the application started with this code:
from fastapi import
FastAPI
app = FastAPI()
This initializes the FastAPI framework. The application needs to instantiate the core
FastAPI
class
from the
fastapi
module and use
app
as the reference variable to the object. Then, this object is
used later as a Python
@app
decorator, which provides our application with some features such as
routes, middleware, exception handlers, and path operations.
Important note
You can replace
app
with your preferred but valid Python variable name, such as
main_app
,
forum
, or
myapp
.
Now, your application is ready to manage REST APIs that are technically Python functions. But to
declare them as REST service methods, we need to decorate them with the appropriate HTTP request
method provided by the path operation
@app
decorator. This decorator contains the
get()
,
post()
,
delete()
,
put()
,
head()
,
patch()
,
trace()
, and
options()
path operations, which
correspond to the eight HTTP request methods. And these path operations are decorated or annotated
on top of the Python functions that we want to handle the request and response.
In our specimen, the first sample that the REST API created was this:
Chia sẻ với bạn bè của bạn: |