【Python】FastAPI – A Fast Web Framework that Competes with Go and Node.js

Posted by


Introduction to FastAPI:

FastAPI is a high-performance web framework for building APIs with Python 3.6+ based on standard Python type hints. It is designed to be fast, easy to use, and highly productive. FastAPI is built on top of Starlette for the web server and Pydantic for data validation and serialization, making it a powerful and efficient tool for building web applications.

In this tutorial, we will cover the basics of FastAPI and show you how to create a simple API using this framework.

Installation:

To install FastAPI, you can use pip, which is the Python package installer. Open your terminal and run the following command:

pip install fastapi[all]

This will install FastAPI along with its dependencies, such as Starlette and Pydantic.

Creating a FastAPI app:

To create a FastAPI app, you need to create a Python file and import the necessary modules. Here is an example of a simple FastAPI app:

from fastapi import FastAPI

app = FastAPI()

@app.get('/')
async def read_root():
    return {'message': 'Hello, World!'}

In this example, we create a FastAPI app using the FastAPI class from the fastapi module. We define a single route using the app.get() decorator, which maps the root URL (‘/’) to the read_root() function. When the root URL is accessed, the read_root() function is called, returning a JSON response with the message ‘Hello, World!’.

Running the FastAPI app:

To run the FastAPI app, you can use the uvicorn CLI tool, which is a lightning-fast ASGI server. In your terminal, run the following command:

uvicorn app:app --reload

This command starts the uvicorn server and loads the app from the app.py file. The –reload flag enables automatic reloading of the server when changes are made to the source code.

Accessing the FastAPI app:

Once the FastAPI app is running, you can access it in your web browser by navigating to http://localhost:8000/. You should see the message ‘Hello, World!’ displayed on the page.

Creating API endpoints:

FastAPI makes it easy to create API endpoints by defining functions with the desired route and HTTP method. You can also specify request and response models using Pydantic data models to enforce data validation and serialization.

Here is an example of creating API endpoints with FastAPI:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = None

@app.post('/items/')
async def create_item(item: Item):
    return {'name': item.name, 'price': item.price, 'is_offer': item.is_offer}

@app.get('/items/{item_id}')
async def read_item(item_id: int, q: str = None):
    return {'item_id': item_id, 'q': q}

In this example, we define two API endpoints: /items/ for creating items with a POST request and /items/{item_id} for reading items with a GET request. We use Pydantic data models to define the structure of the request and response data.

Testing the API endpoints:

To test the API endpoints, you can use tools like curl, Postman, or the browser. For example, you can use curl to send a POST request to create a new item:

curl -X POST 'http://localhost:8000/items/' -H 'Content-Type: application/json' -d '{"name": "Apple", "price": 1.50, "is_offer": true}'

This command sends a POST request to the /items/ endpoint with a JSON payload containing the item data. You should receive a JSON response with the item details.

Conclusion:

FastAPI is a powerful web framework for building APIs with Python that offers high performance, ease of use, and productivity. In this tutorial, we covered the basics of FastAPI, including installation, creating a FastAPI app, running the app, creating API endpoints, and testing the endpoints. FastAPI is a great choice for developers looking to build fast and efficient web applications with Python.

0 0 votes
Article Rating

Leave a Reply

10 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@ArisHuang-m5h
4 hours ago

真簡單,難怪一堆人用

@tomjerry5144
4 hours ago

不谈并发,谈快慢,就是刷流氓

@jerryhuang3565
4 hours ago

這年頭除非專案非常小,要不然前後端越拆越開,正常不會用JS以外語言干涉前端生成,前端幾乎等於全端,但是很多重要的背景任務會丟給API處理,尤其GraphQL真的好用,不過NodeJS庫還是沒有Python厲害,而且Python開發成本低非常多,FastAPI這些年了,到現在依然顯得非常好用

@laopaofr
4 hours ago

会开完整的学习视频吗?

@jojozhao483
4 hours ago

FastAPI 快取决于 uvloop 和 异步编程,我测了一下确实和Go 下的Gin 效率几呼不分上下.

@boscofang2778
4 hours ago

鉴权方面呢?

@游学电子
4 hours ago

支持fastapi,我目前用它来做聊天类应用的服务器端,那是相当的效率了.

@zhengezail9602
4 hours ago

老师您好,请问有付费的完整fastapi课程学习吗?谢谢

@mathcyang
4 hours ago

原来python的web开发不输go与node.js

@yvjvmta2168
4 hours ago

期待API課程 😀

10
0
Would love your thoughts, please comment.x
()
x