This is the first day of my participation in the August Challenge. For details, see:August is more challenging

What is FastApi

As the name suggests, FastApi is a Web framework for building high-performance apis.

The characteristics of FastApi

  • Fast: Comparable to NodeJs and Go
  • Efficient: Development efficiency is more than doubled
  • Less bugs: Reduced development error rates
  • Intelligence: Automatic completion
  • Simple: Easy to learn
  • Brevity: Keep the code short and snappy
  • Robust: Production level available
  • Documentation: Automatically generates interactive documents
  • Standardized: Based on OpenApi

The installation of FastApi

pip install fastapi[all]
Copy the code

FastApi之hello world

main.py

from fastapi import FastAPI

app = FastAPI()

@app.get('/')
async def root() :
    return {'message':'hello world! '}
Copy the code

Command line startup

Exe main:app --reload INFO: uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [18784] using statreload INFO: Started server process [23504] INFO: Waiting for application startup. INFO: Application startup complete.Copy the code

Go to http://127.0.0.1:8000 to see the effect

As you can see, the daemon has returned successfully.

Main function start

from fastapi import FastAPI
import uvicorn

app = FastAPI()

@app.get('/')
async def root() :
    return {'message':'hello world! '}

if __name__ == "__main__":
    uvicorn.run(app='main:app',host='127.0.0.1',port=8765,reload=True,debug=True)
Copy the code

Activation:

python main.py
Copy the code

Interactive API documentation

docs

Browser access: 127.0.0.1:8765/docs

Expand to see interface details

Click Try it on the right

Can realize interface debugging!

Perfect!

redoc

Browser access: 127.0.0.1:8765/redoc

The difference between FastApi and Flask

It’s not uncommon to see people comparing FastAPI to Flask, but not realize that they’re two different things — the former is a framework on top of Starlette with Web API functionality support, The latter is a generic Web framework in the same category as Starlette, so it’s not the same thing, so don’t force comparisons and choose what’s right for you.

As for FastApi’s use of Asyncio and its performance improvement, in my opinion, it is not as exaggerated as the online introduction. With the support of gevent, other web frameworks can also achieve high concurrency, and the general service will use middleware and cluster to achieve high concurrency, so for FastApi’s high performance people are rational. Those of you who are interested can test it and see the actual results.

This series is about introducing the FastApi, a new Web framework, so you can get a feel for it and use it properly.

This concludes the brief introduction to the FastApi.

Thank you for reading, and don’t forget to follow, like, comment, and forward four times!