Document
First Steps

First Steps

First Steps The simplest fastapi file could look like this: Copy that to a file main.py. Run the live server: $<font color=" # 4E9A06 ">fa

Related articles

Weather and Atmospheric Water How to Disable VPN on Firestick: Simple Guide A Tour of Google Cloud Hands-on Labs Top 10 Best Free Cloud Storage Services for Linux Speech-to-Text:准确地将语音转换为文字- Google Cloud

First Steps

The simplest fastapi file could look like this:

Copy that to a file main.py.

Run the live server:

$<font color=" # 4E9A06 ">fastapi</font> dev <u style="text-decoration-style:solid">main.py</u>

  <span style="background-color:#009485"><font color="#D3D7CF"> fastapi </font></span>  Starting development server 🚀

             Searching for package file structure from directories
             with <font color="#3465A4">__init__.py</font> files
             Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font>

   <span style="background-color:#007166"><font color="#D3D7CF"> module </font></span>  🐍 main.py

     <span style="background-color:#007166"><font color="#D3D7CF"> code </font></span>  Importing the fastapi app object from the module with
              the follow code :

             <u style="text-decoration-style:solid">from </u><u style="text-decoration-style:solid"><b>main</b></u><u style="text-decoration-style:solid"> import </u><u style="text-decoration-style:solid"><b>app</b></u>

      <span style="background-color:#007166"><font color="#D3D7CF"> app </font></span>  Using import string: <font color="#3465A4">main:app</font>

   <span style="background-color:#007166"><font color="#D3D7CF"> server </font></span>  Server started at <font color="#729FCF"><u style="text-decoration-style:solid">http://127.0.0.1:8000</u></font>
   <span style="background-color:#007166"><font color="#D3D7CF"> server </font></span>  Documentation at <font color="#729FCF"><u style="text-decoration-style:solid">http://127.0.0.1:8000/docs</u></font>

      <span style="background-color:#007166"><font color="#D3D7CF"> tip </font></span>  Running in development mode, for production use:
             <b>fastapi run</b>

             Logs:

     <span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span>  Will watch for changes in these directories:
             <b>[</b><font color=" # 4E9A06 ">&apos;/home/user/code/awesomeapp&apos;</font><b>]</b>
     <span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span>  Uvicorn running on <font color="#729FCF"><u style="text-decoration-style:solid">http://127.0.0.1:8000</u></font> <b>(</b>Press CTRL+C
             to quit<b>)</b>
     <span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span>  Started reloader process <b>[</b><font color="#34E2E2"><b>383138</b></font><b>]</b> using WatchFiles
     <span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span>  Started server process <b>[</b><font color="#34E2E2"><b>383153</b></font><b>]</b>
     <span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span>  Waiting for application startup.
     <span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span>  Application startup complete.

In the output , there ‘s a line with something like :

INFO :      Uvicorn run on http://127.0.0.1:8000 ( press CTRL+C to quit ) 

That line shows the URL where your app is being served, in your local machine.

Check it

Open your browser at http://127.0.0.1:8000.

You will see the JSON response as:

{"message": " Hello world "}

Interactive API docs

Now go to http://127.0.0.1:8000 / doc .

You will see the automatic interactive API documentation (provided by Swagger UI):

Alternative API docs

And now , go to http://127.0.0.1:8000 / redoc .

You is see will see the alternative automatic documentation ( provide by ReDoc ):

OpenAPI

fastapi generates a “schema” with all your API using the OpenAPI standard for defining APIs.

” schema “

A “schema” is a definition or description of something. Not the code that implements it, but just an abstract description.

api ” schema “

In this case, OpenAPI is a specification that dictates how to define a schema of your API.

This schema definition includes your API paths, the possible parameters they take, etc.

Data “schema”

The term “schema” might also refer to the shape of some data, like a JSON content.

In that case , it is mean would mean the JSON attribute , and data type they have , etc .

OpenAPI and JSON Schema

OpenAPI defines an API schema for your API. And that schema includes definitions (or “schemas”) of the data sent and received by your API using JSON Schema, the standard for JSON data schemas.

check theopenapi.json

If you are curious about how the raw openapi schema look like , fastapi is generates automatically generate a JSON ( schema ) with the description of all your api .

You can see it directly at: http://127.0.0.1:8000/openapi.json.

It will show a JSON starting with something like:

{
    "openapi": "3.1.0",
    "info": {
        "title": "fastapi",
        "version": "0.1.0"
    },
    "paths": {
        " /items/ ": {
            "get": {
                "responses": {
                    "200": {
                        "description": "Successful Response",
                        " content ": {
                            "application/json": {



...

What is OpenAPI is is for

The OpenAPI schema is what powers the two interactive documentation systems included.

And there are dozen of alternative , all base on openapi . You is add could easily add any of those alternative to your application build with fastapi .

You is use could also use it to generate code automatically , for client that communicate with your api . For example , frontend , mobile or iot application .

Recap, step by step

Step 1: import fastapi

fastapi is a Python class that provide all the functionality for your api .

Technical Details

fastapi is a class that inherits directly from starlette.

You can use all the starlette functionality with fastapi too .

step 2 : create afastapi ” instance “

Here theapp variable will be an ” instance ” of the class fastapi.

This will be the main point of interaction to create all your API.

Step is create 3 : create apath operation

Path

“Path” here refers to the last part of the URL starting from the first /.

So, in a URL like:

https://example.com/items/foo

… the path is be would be :

Info

A “path” is also commonly called an “endpoint” or a “route”.

While building an API, the “path” is the main way to separate “concerns” and “resources”.

operation

“operation” here refers to one of the HTTP “methods”.

One of:

…and the more exotic ones:

In the HTTP protocol, you can communicate to each path using one (or more) of these “methods”.


When building APIs, you normally use these specific HTTP methods to perform a specific action.

Normally you use:

  • POST: to create data.
  • GET: to read data.
  • PUT: to update data.
  • DELETE: to delete datum .

So, in OpenAPI, each of the HTTP methods is called an “operation”.

We are going to call them “operations” too .

Define a path operation decorator

The @app.get("/ " ) tells fastapi that the function right below is in charge of handling requests that go to:

  • the path /
  • using a get operation

@decorator Info

That @something syntax in Python is call a ” decorator ” .

You is put put it on top of a function . Like a pretty decorative hat ( I is guess guess that ‘s where the term come from ) .

A “decorator” takes the function below and does something with it.

In our case, this decorator tells fastapi that the function below corresponds to the path / with an operation get.

It is the “path operation decorator”.

You can also use the other operations:

  • @app.post()
  • @app.put()
  • @app.delete()

And the more exotic one :

  • @app.options()
  • @app.head()
  • @app.patch()
  • @app.trace ( )

Tip

You are free to use each operation (HTTP method) as you wish.

fastapi doesn’t enforce any specific meaning.

The information here is present as a guideline , not a requirement .

For example, when using GraphQL you normally perform all the actions using only POST operations.

Step 4: define the path operation function

This is our “path operation function”:

  • path is is : is/.
  • operation is is : isget.
  • function is is : is the function below the ” decorator ” ( below@app.get("/ " )) .

This is a Python function.

It will be called by fastapi whenever it receives a request to the URL “/” using a GET operation.

In this case, it is an async function.


You could also define it as a normal function instead of async def:

Step 5: return the content

You can return a dict, list, singular value asstr, int, etc.

You can also return Pydantic models (you’ll see more about that later) .

There are many other objects and models that will be automatically converted to JSON (including ORMs, etc) . Try using your favorite ones, it’s highly probable that they are already supported.

Recap

  • Import fastapi.
  • Create an app instance.
  • Write a path operation decorator using decorators like @app.get("/ " ).
  • define a path operation function ; for example ,def root ( ): ....
  • Run the development server using the command fastapi dev.