Learnmonkey Learnmonkey Logo
× Warning:

The tutorial you are reading is currently a work in-progress.

Your First FastAPI API

Writing the Code

Below is what our code is going to look like:


from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def hello_world():
    return {"message": "Hello FastAPI!"}
    

Then, save the above code in a file called main.py.

Running the Code

Actually, you cannot run the code as a normal Python file. Instead, you need to run:

python -m uvicorn main:app --reload

The main part of the command refers to the file we saved our code in, main.py.

The app part refers to the name of the FastAPI() object we created.

Finally, the --reload flag makes the server restart every time you change the code. This should only be used for development.

Once you run it, you should see something like:


INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [28720]
INFO:     Started server process [28722]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

You should now be able to go to 127.0.0.1:8000 and see:

{"message":"Hello FastAPI!"}

Interactive API Docs

One cool feature of FastAPI is that when you make your API, FastAPI automatically generates interactive API docs. You can find it by going to 127.0.0.1:8000/docs. If you don't like it, there is an alternative version which you can find by going to 127.0.0.1:8000/redoc.

FastAPI generates these API docs by first generating a schema for your API. This schema is called OpenAPI. The two interactive API docs are powered by OpenAPI. OpenAPI can also be used to generate code that interact with your API. You can find the raw OpenAPI schema at 127.0.0.1:8000/openapi.json.

Code Breakdown

Now, let's breakdown the code we've wrote.

First of all, we need to import the FastAPI stuff we need:

from fastapi import FastAPI

Then, we create an instance of the FastAPI class, which provides all the functionality of our API:

app = FastAPI()

Then, we use a decorator (something that modifies the next function) on top of our function that returns our response. The decorator tells FastAPI to return whatever the next function returns and return that to the user when they go to the root of our API (a GET request):

@app.get("/")

Then, we actually write the function. In this case it is async, but you could've just as easily used a normal function:

async def hello_world():

For more information on whether to use an asynchrnous function or a normal function, click here.

Then, we return a dictionary which represents our JSON response:

return {"message":"Hello FastAPI!"}

And that's it!