# Unit 5: Hello World!

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

{% code lineNumbers="true" %}

```python
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}"}
```

{% endcode %}

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

```
uvicorn main:app --reload --port 8080
```

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.
* `--port 8080`: (optional) used to specifically define the listening port

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:

```json
{"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

FastAPI automatically generates an API Docs for your project, provided by [Swagger UI](https://github.com/swagger-api/swagger-ui). The API Docs is available at `http://127.0.0.1:8000/docs`, as shown in Fig. 1.

<figure><img src="https://4188609209-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhp4eambztJcKKLa7ysKG%2Fuploads%2Fwn4vKrwF72wdSYUka3Ex%2FScreenshot%202024-01-19%20at%205.32.09%20PM.png?alt=media&#x26;token=0b920db7-1b6e-4452-99f6-54b06b1bc4b9" alt=""><figcaption><p>Fig. 1. An example of API Docs generated by FastAPI, provided by <a href="https://github.com/swagger-api/swagger-ui">Swagger UI</a></p></figcaption></figure>

Besides API Docs provided by Swagger UI, FastAPI also generate another API Docs provided by [ReDoc](https://github.com/Rebilly/ReDoc), available at `http://127.0.0.1:8000/redoc`, as shown in Fig. 2.

<figure><img src="https://4188609209-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhp4eambztJcKKLa7ysKG%2Fuploads%2F8Q1HS7SjfVMJ3cOHar5u%2FScreenshot%202024-01-19%20at%205.35.02%20PM.png?alt=media&#x26;token=9031dde8-dc2c-4064-9834-57d84a056810" alt=""><figcaption><p>Fig. 2. An example of API Docs generated by FastAPI, provided by <a href="https://github.com/Rebilly/ReDoc">ReDoc</a></p></figcaption></figure>

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

{% hint style="info" %}
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.
{% endhint %}

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

{% code overflow="wrap" %}

```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"
            }
        }
    }
}
```

{% endcode %}

***

## 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).

{% hint style="info" %}
A "path" is also commonly called an "endpoint" or a "route".
{% endhint %}
