CS504070 - FastAPI Tutorials
  • 🧩CS504070 - FastAPI Tutorials
  • 🔎Unit 1: Python Type Hint
  • ⚙️Unit 2: Pydantic
  • 🔃Unit 3: Concurrency
  • 💾Unit 4: Install FastAPI
  • 🍉Unit 5: Hello World!
  • 🍌Unit 6: Path Parameters
  • 🍋Unit 7: Query Parameters
  • 🍊Unit 8: Request Body
  • 🍐Unit 9: Query Parameters and Validations
  • 🍎Unit 10: Path Parameters and Validations
  • 🍏Unit 11: Multiple Parameters
  • 🍇Unit 12: Request Body - List Fields and Nested Models
  • 🍓Unit 13: Data Types
  • 🍪Unit 14: Cookie Parameters
  • 🫐Unit 15: Header Parameters
  • 🍈Unit 16: Response Model - Return Type
  • 🍒Unit 17: Additional Models
  • 🥑Unit 18: Implementing JWT Authentication with FastAPI
  • ⚙️Appendix A
  • 🍭Appendix B
Powered by GitBook
On this page
  • Interactive API docs
  • Summary

Unit 5: Hello World!

In this unit, you will take the first step towards understanding the program structure of FastAPI and learning how to run your program.

Let's create a new main.py file and insert the following code into it:

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}

To run the above program, open a CMD/Terminal and execute the command below:

uvicorn main:app --reload

The command uvicorn main:app refers to:

  • main: the file main.py (the Python "module").

  • app: the object created inside of main.py with the line app = FastAPI().

  • --reload: make the server restart after code changes. Only use for development.

If your program is error-free, below is the result when executing the above command:

uvicorn main:app --reload
INFO:     Will watch for changes in these directories: ['/Users/Dev/Projects/fastApiProject']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [4079] using WatchFiles
INFO:     Started server process [4081]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Open your browser at http://127.0.0.1:8000 and you will get a JSON response as:

{"message": "Hello World"}

To test the say_hello() function, change the address to http://127.0.0.1:8000/hello/<name> where <name> is a variable.


Interactive API docs

To ensure compatibility with standard HTTP APIs, FastAPI uses the OpenAPI standard for defining APIs.

The OpenAPI Specification (OAS) defines a standard, programming language-agnostic interface description for HTTP APIs. This allows both humans and computers to discover and understand the capabilities of a service without requiring access to source code, additional documentation, or inspection of network traffic. When properly defined via OpenAPI, a consumer can understand and interact with the remote service with a minimal amount of implementation logic.

OpenAPI documents describe API services and are represented in YAML or JSON formats. These documents may be produced and served statically or generated dynamically from an application.

For our Hello World program, you can see openapi.json directly at http://127.0.0.1:8000/openapi.json.

{
    "openapi": "3.1.0",
    "info": {
        "title": "FastAPI",
        "version": "0.1.0"
    },
    "paths": {
        "/": {
            "get": {
                "summary": "Root",
                "operationId": "root__get",
                "responses": {
                    "200": {
                        "description": "Successful Response",
                        "content": {
                            "application/json": {
                                "schema": {}
                            }
                        }
                    }
                }
            }
        },
        "/hello/{name}": {
            "get": {
                "summary": "Say Hello",
                "operationId": "say_hello_hello__name__get",
                "parameters": [
                    {
                        "name": "name",
                        "in": "path",
                        "required": true,
                        "schema": {
                            "type": "string",
                            "title": "Name"
                        }
                    }
                ],
                "responses": {
                    "200": {
                        "description": "Successful Response",
                        "content": {
                            "application/json": {
                                "schema": {}
                            }
                        }
                    },
                    "422": {
                        "description": "Validation Error",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/HTTPValidationError"
                                }
                            }
                        }
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "HTTPValidationError": {
                "properties": {
                    "detail": {
                        "items": {
                            "$ref": "#/components/schemas/ValidationError"
                        },
                        "type": "array",
                        "title": "Detail"
                    }
                },
                "type": "object",
                "title": "HTTPValidationError"
            },
            "ValidationError": {
                "properties": {
                    "loc": {
                        "items": {
                            "anyOf": [
                                {
                                    "type": "string"
                                },
                                {
                                    "type": "integer"
                                }
                            ]
                        },
                        "type": "array",
                        "title": "Location"
                    },
                    "msg": {
                        "type": "string",
                        "title": "Message"
                    },
                    "type": {
                        "type": "string",
                        "title": "Error Type"
                    }
                },
                "type": "object",
                "required": [
                    "loc",
                    "msg",
                    "type"
                ],
                "title": "ValidationError"
            }
        }
    }
}

Summary

The Hello World program can best describe the procedure for programming your first APIs with FastAPI, which includes several important steps as follows:

  1. Import FastAPI module

  2. Create a FastAPI instance, for example, app = FastAPI(). You should note that the app variable is the same one referred by uvicorn in the execution command.

  3. Create functions in conjunction with path operations.

    1. Path refers to the last part of the URL starting from the first /, for example, given an URL as https://example.com/items/foo, the path would be /items/foo.

    2. Operation refers to the HTTP methods such as POST, GET, PUT, DELETE.

    3. Define a path operation decorator as @app.get("/"). 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.

  4. Define the path operation function that is specified below the decorator, for example, async def root().

  5. Return the content such as a dict, list, singular values as str, int, etc. There are many other objects and models that will be automatically converted to JSON (including ORMs, etc).

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

PreviousUnit 4: Install FastAPINextUnit 6: Path Parameters

Last updated 1 year ago

FastAPI automatically generates an API Docs for your project, provided by . The API Docs is available at http://127.0.0.1:8000/docs, as shown in Fig. 1.

Besides API Docs provided by Swagger UI, FastAPI also generate another API Docs provided by , available at http://127.0.0.1:8000/redoc, as shown in Fig. 2.

Swagger UI
ReDoc
🍉
Fig. 1. An example of API Docs generated by FastAPI, provided by
Fig. 2. An example of API Docs generated by FastAPI, provided by
Swagger UI
ReDoc
Page cover image