Creating Your Initial Python API with FastAPI

Posted by


FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. In this tutorial, we will walk you through creating your first Python API using FastAPI.

Step 1: Setting up your environment
Before you start, make sure you have Python 3.6+ installed on your machine. You can check your Python version by running python --version in your terminal.

Next, create a new directory for your project and navigate there in your terminal. Then, create a virtual environment by running:

python -m venv env

Activate the virtual environment by running:

source env/bin/activate

Now, install FastAPI and Uvicorn, which is a lightning-fast ASGI server for Python, using pip:

pip install fastapi uvicorn

Step 2: Creating your first FastAPI app
Create a new Python file, for example, main.py, in your project directory. In this file, import FastAPI and create a FastAPI instance:

from fastapi import FastAPI

app = FastAPI()

Step 3: Defining routes
Routes are the endpoints of your API that clients can interact with. Define routes using FastAPI by creating functions with the @app.get or @app.post decorators. For example, let’s create a simple "Hello, World!" route:

@app.get('/')
async def read_root():
    return {"message": "Hello, World!"}

Step 4: Running your FastAPI app
To run your FastAPI app, use Uvicorn to start the ASGI server. Run the following command in your terminal:

uvicorn main:app --reload

Now, you can access your FastAPI app at http://127.0.0.1:8000 in your browser or using a tool like Postman.

Step 5: Testing your API
You can test your API endpoints using the Swagger UI that FastAPI generates for you. Navigate to http://127.0.0.1:8000/docs in your browser to access the Swagger documentation and interact with your API.

Step 6: Adding more routes
You can add more routes to your FastAPI app by creating new functions with the @app.get or @app.post decorators. Include the route path in the decorator to define the endpoint URL. Here’s an example of adding a new route to retrieve a specific item by ID:

@app.get('/items/{item_id}')
async def read_item(item_id: int):
    return {"item_id": item_id}

Step 7: Adding request bodies
You can also receive data in the request body of your API endpoints by defining a Pydantic model and including it as a parameter in your route function. Here’s an example of adding a route to create a new item with a request body:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str

@app.post('/items/')
async def create_item(item: Item):
    return item

That’s it! You have just created your first Python API using FastAPI. FastAPI provides many more features, such as dependency injection, response models, and validations, that you can explore to build powerful and efficient APIs. Check out the FastAPI documentation for more information and examples: https://fastapi.tiangolo.com/.

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x