Setting Up FastAPI for Starters
6
The preceding is a
GET
API service method that returns a
JSON
object. To locally
run our application,
we need to execute the following command:
uvicorn main:app --reload
This command will load the forum application to the uvicorn live server through the application’s
main.py
file with FastAPI object referencing. Live reload is allowed by adding the
--reload
option, which enables the restart of the development server whenever there are changes in the code.
Figure 1.1 – The
uvicorn console log
Figure 1.1 shows that uvicorn uses
localhost
to run the application with the default port
8000
.
We can access our index page through
http://localhost:8000/ch01/index
. To stop the
server, you just need to press the
Ctrl +
C keyboard keys.
After
running our first endpoint, let us now explore how to implement the other types of HTTP
methods, namely
POST
,
DELETE
,
PUT
, and
PATCH
.
Designing and implementing REST APIs
The
Representation State Transfer
(
REST
) API makes up the rules, processes, and tools that allow
interaction among microservices. These are method services that are identified and executed through
their endpoint URLs. Nowadays, focusing on API methods before building a whole application is one
of the most popular and effective microservices design strategies.
This approach, called an
API-first
microservices development, focuses first on the client’s needs and then later
identifies what API service
methods we need to implement for these client requirements.
In our
online academic discussion forum app, software functionality such as
user sign-up,
login,
profile
management,
message posting, and
managing post replies are some of the crucial needs we prioritized.
In a FastAPI framework, these features are implemented as services using functions that are defined
using Python’s
def
keyword, with the association of the appropriate
HTTP request method through
the
path operations provided by
@app
.
The
login
service, which requires
username
and
password
request parameters from the user,
is implemented as a
GET
API method:
Chia sẻ với bạn bè của bạn: