Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of constructing API Service by FastAPI

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

Today, I will talk to you about the example analysis of building API services by FastAPI. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.

FastAPI is a high-performance framework for building API services.

Why choose FastAPI?

FastAPI is a modern, high-performance web framework for building APIs based on Python version 3.6 and above.

The biggest feature: come on! The performance is extremely high, which can be comparable with NodeJS and Go.

Based on Starlette and Pydantic, it is an important reason why FastAPI has such a high performance.

It also has the advantages of high code reusability, easy to use and strong robustness.

Personally, I also think that FastAPI also has a very strong advantage: convenient API debugging, generate API documents, directly can debug their own API, which in practical applications, the value is prominent.

FastAPI is so strong that it is necessary to study and use it, because no matter doing development or algorithm, API service is really too important, especially for large manufacturers, can not do without API interface.

Pydantic does type mandatory check

FastAPI is based on Pydantic, and Pydantic is mainly used for type enforcement checking. If the parameter assignment does not meet the type requirements, an exception will be thrown.

For API services, supporting type checking is very useful, making the service more robust and speeding up development, because developers no longer have to write their own line of type checking.

First of all, pip install pydantic

Then, use Pydantic to do mandatory type checking.

From pydantic import ValidationError

From datetime import datetime

From typing import List

From pydantic import BaseModel

Class User (BaseModel):

Id:int

Name='jack guo'

Signup_timestamp: datetime = None

Friends: List [int] = []

It was observed that:

Id requirements must be intname requirements must be str, and there is a default value signup_timestamp requires datetime, default value Nonefriends requires List, element type requires int, default value is []

Use the User class:

Try:

User (signup_timestamp='not datetime',friends= [1, 2, 3, not number'])

Except ValidationError as e:

Print (e.json ())

Id has no default value and will report missing exceptions as expected

Signup_timestamp is assigned a non-datetime type value and will report an exception as expected

An element with an friends index of 3 is assigned to str and an exception is expected.

Execute the code to verify that it meets expectations.

The implementation results show that it is in line with expectations.

[

{

"loc": [

"id"

]

"msg": "field required"

"type": "value_error.missing"

}

{

"loc": [

"signup_timestamp"

]

"msg": "invalid datetime format"

"type": "value_error.datetime"

}

{

"loc": [

"friends"

three

]

"msg": "value is not a valid integer"

"type": "type_error.integer"

}

]

Get started with FastAPI quickly

This is a starter demo that builds the following three routes:

From fastapi import FastAPI

From pydantic import BaseModel

App = FastAPI ()

Class User (BaseModel):

Id: int

Name: str

Friends: list

@ app.get ("/")

Def index ():

Return {"admin": "welcome to FastAPI"}

@ app.get ("/ users/ {user_id}")

Def read_user (user_id: int, name: str = None):

Return {"user_id": user_id, "name": name}

@ app.put ("/ users/ {user_id}")

Def update_user (user_id: int, user: User):

Return {"user_name": user.name, "user_id": user_id}

Save the above code as main.py

Reinstall the framework uvicorn related to the build service

After the installation is completed, the background executes: uvicorn main:app-- reload

Start the service and display as follows:

Open the client, enter: localhost:8000, enter:

Input request: localhost:8000/users/5, enter, see the foreground data, very easy to transfer to the controller layer, convenient.

Enter request: localhost:8000/docs, enter:, see the API document interface

Click on the second get request, and then click Try it out to debug the interface. It's very convenient!

After entering user_id and name, click Execute to execute successfully. If the user_id input is non-numeric, after clicking Execute, the red box flashes and will not be executed until the input is correct.

After entering user_id, name, click Execute

You can see the results, including the requested URL

You can also see the result returned by the server responding to the front end:

After reading the above, do you have any further understanding of the sample analysis of FastAPI building API services? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report